- æ¦è¦
- __main__ ã復ç¿
- ãããã__main__.py ãããã¨ã©ããªãï¼
- ã©ãããã¨ãã«ä¾¿å©ï¼
- è£è¶³
æ¦è¦
ç®ããé±ã®æ
å ±ã ã£ãã®ã§ãå¿ããªããã¡ã«ã¡ã¢ã¡ã¢ãããããã°ããã ãï½ã£ã¦ãªãã¾ãããç¥ããªãã£ãã®ãæ¥ããããã§ãããããããã°ãGithub ã¨ãã§ã ãã __main__.py
ãã¡ã¤ã«è¦ããã¦ãã¾ããã
__main__.py
ã使ãã¾ãããã£ã¦è¨äºã§ãã
__main__
ã復ç¿
python ãã£ã¦ã人ã ã¨ã»ã¼å ¨å¡ä»¥ä¸ãæ¸ãã¦ãã or æ¸ãããã¨ãããã¯ãã§ãã
if __name__ == "__main__": # å¦ç
python ã¤ã³ã¿ã¼ããªã¿ã¼ã¯ããã¡ã¤ã«ãæå®ããã¦èµ·åããå ´å ç¹æ®å¤æ° __name__
ã« __main__
ã¨ããå¤ãè¨å®ãã¦ãããã®ã§ãããã«ããããã® ã¹ã¯ãªãããã¡ã¤ã« ãä»ã®ã¹ã¯ãªãããã import ããã¦å¼ã°ããã®ããpython ã¤ã³ã¿ã¼ããªã¿ã¼ã§ç´æ¥æå®ãããèµ·åããã®ããè¦åãããã¨ãåºæ¥ãã£ã¦ãã¤ã§ãããã©ã®æ¬ã«ãæ¸ãã¦ããå
容ã§ãã
ãããã__main__.py
ãããã¨ã©ããªãï¼
ä¸ã®åç
§è¨äºã§ã詳ããæ¸ãã¦ãã ãã£ã¦ã¾ããã__main__.py
ãããã¦ããã¨ãpython ã¤ã³ã¿ã¼ããªã¿ã¼ã«ã¦
-m ãªãã·ã§ã³ã§ããã±ã¼ã¸æå®ãã¦èµ·åããéã« ã¡ã¤ã³ãã¡ã¤ã« ã¨ãã¦èªã¿è¾¼ã¾ãã
ã¨ãããã¨ã«ãªãã¾ãã
ã©ãããã¨ãã«ä¾¿å©ï¼
ç°¡åãªä½¿ãæ¨ã¦ã¹ã¯ãªããã ã¨ï¼ãã¡ã¤ã«ãªã®ã§
$ python hoge.py
ã¨ããã£ã¦ãèµ·åããã¦ãã¾ãã®ã§ãããã¡ãã£ã¨ãããã¼ã«ä½ãã¨ãã¨ãã¯ããã±ã¼ã¸æ§æã«ãããã¨ãå¤ãã§ããã
ä¾ãã°
$ tree -L 2 . âââ pkg1 â âââ __init__.py â âââ __main__.py â âââ __pycache__ âââ pkg2 â âââ __init__.py â âââ __pycache__ â âââ main.py âââ venv âââ bin âââ include âââ lib âââ pyvenv.cfg
ãããªé¢¨ã« pkg1 㨠pkg2 ã£ã¦æ§æã«ãã¦ããã¨ãã¦(ã¡ãã£ã¨å¤ã§ãã説æç¨ã£ã¦ãã¨ã§)ãpkg1ã®æ¹ã«ã¯ __main__.py
ãããã¦ããã¾ãã pkg2ã®æ¹ã¯ æ®éã« main.py ã£ã¦ååã§ãã¡ã¤ã«ããã¦ããã¾ããä¸èº«ã¯ãããªæãã
__main__.py
(pkg1)
print("hello pkg1")
- main.py (pkg2)
if __name__ == "__main__": print("hello pkg2")
pkg1 ã®å ´åã-m
ãªãã·ã§ã³ã¤ãã¦å¼ã¶å ´åã¯ã以ä¸ã®ããã«åºæ¥ã¾ãã
$ python -m pkg1
pkg2 ã®å ´åã以ä¸ã®ããã«ããªãã¨åãã¦ããã¾ããã
$ python -m pkg2.main
pkg1 ã¨åãããã«èµ·åãã¦ã¿ãã¨
$ python -m pkg2 python: No module named pkg2.__main__; 'pkg2' is a package and cannot be directly executed
ã£ã¦æããã¾ãã
pkg1ã®å ´åã ã¨ãããã±ã¼ã¸åãæå®ãã¦ããã ããªã®ã§ãå人çã«ããã楽ã
ãã¨ã__main__.py
ã®å ´åã ã¨ã-m
ã¤ãã¦ããã±ã¼ã¸æå®ãããéã«å¼ã°ããã®ã確å®ãã¦ãã®ã§ããããã
if __name__ == "__main__": # å¦ç
ã£ã¦æ¸ããªãã¦ãããã®ã楽ã
é å¸ã¨ãããªãèªåãã¼ã«ãããã±ã¼ã¸èµ·åããå ´åã¨ãã«ä¾¿å©ã
è£è¶³
ä¸ã®ä¾ã¯ããã¾ã§ -m
ãªãã·ã§ã³ã¤ãã¦å¼ã¶å ´åã®è©±ã§ããsetup.py
ãä½ã£ã¦ console_scripts ã§å®ç¾©ãã¦
$ pip install -e .
ã¨ããã¦ä½¿ãå ´åãsetup.py
ã«ã¯
entry_points={ 'console_scripts': [ 'pkg1=pkg1.__main__:main' ] }
ã¿ããã«é¢æ°æå®ãã¦æ¸ãå¿
è¦ãããã®ã§ __main__.py
ã«ã¯
def main(): pass if __name__ == "__main__": main()
ã£ã¦æ¸ããããã¾ãã
python-packaging.readthedocs.io
éå»ã®è¨äºã«ã¤ãã¦ã¯ã以ä¸ã®ãã¼ã¸ãããåç §ä¸ããã
- ããããåå¿é²æ¥è¨ã¾ã¨ã
ãµã³ãã«ã³ã¼ãã¯ã以ä¸ã®å ´æã§å ¬éãã¦ãã¾ãã
- ããããåå¿é²æ¥è¨ãµã³ãã«ã½ã¼ã¹ç½®ãå ´