当python解释器读一个源文件的时候,会执行文件里面所有的代码。但是如果python执行一个源文件,作为main program执行的时候,会设置一个__name__变量,这个变量的值为__main__. 当执行主程序的时候使用 if __name == '__name__', 如果值为true,那么python会执行该文件,不管是作为可重复使用的模块或者是一个单独的程序。
如果要python在执行import文件种的函数:
__name __== moudle's name
例如:
test1.py
from test2 import print_hello def print_world(): print ('world') if __name__ == '__main__': print_world() print_hello()
test2.py
def print_hello(): print ('hello') if __name__ == 'test2': print_hello()
单独运行test2.py 无任何打印, 因为没有__name__ == '__main__'
如果运行test1.py, 则会打印hello,word,hello , 首先在import的时候会运行test2.py,然后再运行__name__=='__main__'下的两个函数。
如果要python执行本文件种的函数:
__name __== '__main__'