if __name__ == '__main__'
__name__ == '__main__'
# /home/main_one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# /home/main_two.py
import main_one
print("top-level in two.py")
main_one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
运行main_one.py,输出
top-level in one.py
one.py is being run directly
运行main_two.py,输出
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
我的理解
当一个A脚本被执行时,这时A脚本的
__name__
和"__main__)"
就相等当在B脚本导入A脚本,B脚本执行时,这时A脚本的
__name__
和"__main__)"
就不相等
关于main_two.py执行的问题
对导入的模块来说,模块中的函数是调用时才执行的,但是语句会立刻执行(那些没有缩进的语句)