Pythonの if __name__ == '__main__'についてのメモ
概要
Pythonでのプログラムを実行する際に直接実行した場合にのみこのプログラムを動かすようにするためのものとのこと。 前から仕事でPythonプログラムを見る機会があり、どういう意味かわかっていなかったが、少しだけ理解が進んだ。 Head First Python5章の以下のサンプルプログラムをみてみるとそういう動きをしているようだ。 - サンプルプログラム
print('',__name__)
if __name__=='__main__' :
print('end:',__name__)
- 実行結果
(python3_venv) sysadmin@nucserver01:~/head_first_python_sample$ python3 dunder.py first; __main__ end: __main__
- 対話モードでモジュールとして読み込んだ結果
下記の通り、nameは’dunder’となっている
(python3_venv) sysadmin@nucserver01:~/head_first_python_sample$ python3 Python 3.13.3 (main, May 10 2025, 11:59:01) [GCC 13.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import dunder first; dunder