mainの使い方(how to use main)

def func1(): print('func1 is called')def func2(): print('func2 is called')if __name__=='__main__': sys.exit(main())
if args[1]=='func1': func1() if args[1]=='func2': func2()
def main(): args = sys.argv if len(args) == 1: print('There is no command line arguments. Please specify func1 or func2.') return

import sys

仮に実行サンプルを示すべき関数,func1とfunc2があるファイルに含まれる場合に,それらの実行サンプル部を含む基本的なファイルの構造は下のようにする.ここでmain()を使っているのは,main()を使うことで変数のスコープを汚さないことが主な目的だ.main()を使わずにif __name__=='__main__':の下にmain()の中身を書くことも可能だが,そうした場合にはそこで使われる変数がグローバル変数となってしまい,python の名前空間を汚染して,思わぬそしてデバッグが難しいエラーを引き起こし得る.またmain()を使えば,main()をファイルの最初に置くことで,ユーザーに分かりやすくすることもできる.このファイルを

ipython -i this_file.py func1

と実行する.あるいはipythonまたはpythonのセッションから,run this_file.py func1 などとして実行すると,func1が呼び出される.

python のモジュールファイルが,他から呼び出して使う関数を含む場合,それらの関数の実行サンプルあるいはデバッグのための呼び出しをモジュールに含めたいことがある.特に実行サンプルは同じファイルに含めることで,呼び出し側(実行サンプル)と呼び出される側(関数)との対応が明確になる.

For functions that are used by execution statements of external files, sometimes you may want to include example execution code. To include the execution code in the same file as that of function, users can know the correspondenses between them.

The basic structure of a file that contains two functions, func1 and func2, and their execution codes is shown below. The function main() is executed, when this file is run by, i.e.,

ipython -i this_file.py

The purpose of use of main() compared with not use it (just use "if __name__=='__main__'":) is to avoid possible problems of gobal names.

import sys

def main():

args = sys.argv

if len(args) == 1:

print('There is no command line arguments. Please specify func1 or func2.')

return

if args[1]=='func1':

func1()

if args[1]=='func2':

func2()

def func1():

print('func1 is called')

def func2():

print('func2 is called')

if __name__=='__main__':

sys.exit(main())