Pythonのメイン関数

Pythonのメイン関数は、Pythonプログラムとして実行される場合にのみ実行されます。ご存知のように、Pythonプログラムをモジュールとしてインポートすることもできますが、その場合はPythonのメインメソッドは実行されません。

Pythonのメイン関数

メイン関数は、どんなプログラムでもエントリーポイントです。しかし、Pythonインタープリターはソースファイルのコードを順番に実行し、コードの一部でないメソッドを呼び出しません。ただし、コードの直接の一部である場合は、モジュールとしてインポートされたときに実行されます。そのため、Pythonプログラムでメインメソッドを定義するための特別なテクニックがあります。そのテクニックを使って、プログラムが直接実行される場合にのみ実行されるPythonのメイン関数を定義する方法を見てみましょう。python_main_function.py

print("Hello")

print("__name__ value: ", __name__)


def main():
    print("python main function")


if __name__ == '__main__':
    main()
  • When a python program is executed, python interpreter starts executing code inside it. It also sets few implicit variable values, one of them is __name__ whose value is set as __main__.
  • For python main function, we have to define a function and then use if __name__ == ‘__main__’ condition to execute this function.
  • If the python source file is imported as module, python interpreter sets the __name__ value to module name, so the if condition will return false and main method will not be executed.
  • Python provides us flexibility to keep any name for main method, however it’s best practice to name it as main() method. Below code is perfectly fine, however not recommended.
    def main1():
    print(“python main function”)if __name__ == ‘__main__’:
    main1()
python main function, python if name main

Pythonのメイン関数をモジュールとして使う

では、上記のPythonソースファイルをモジュールとして使用し、別のプログラムにインポートしましょう。python_import.py

import python_main_function

print("Done")
python main method, python if main
Hello
__name__ value:  python_main_function
Done

Python_main_function.pyソースファイルから最初の2行が表示されていることに注意してください。 __name__の値が異なるため、mainメソッドは実行されません。Pythonプログラムの文は、行ごとに実行されるため、mainメソッドをif条件の前に定義することが重要です。そうしないと、NameError: name ‘main’ is not definedというエラーが発生します。これがPythonのメイン関数についてのすべてです。参考:Pythonドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *