这样做做什么,为什么应该包括:if
语句?
if __name__ == "__main__":
print("Hello, World!")
如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数main
自动用作切入点,使用当我启动 Python 脚本时, 主函数为何不运行? 脚本从哪里开始运行 ?.
考虑:
if __name__ == "__main__":
main()
它检查是否__name__
Python 脚本属性是"__main__"
。换句话说,如果程序本身被执行,则属性将是__main__
,因此程序将被执行(在这种情况下,main()
职能)
然而,如果您的 Python 脚本被模块使用,if
将执行语句,所以if __name__ == "__main__"
仅用于检查程序是否用作模块,因此决定是否运行代码。
Python 中每个模块的属性都称为属性__name__
的值。__name__
属性是__main__
当模块直接运行时, 例如python my_module.py
否则(就像你说的那样)import my_module
)值的数值__name__
是模块的名称。
简而言之,仅举一个小例子来解释。
脚本测试.py
apple = 42
def hello_world():
print("I am inside hello_world")
if __name__ == "__main__":
print("Value of __name__ is: ", __name__)
print("Going to call hello_world")
hello_world()
我们可以直接执行
python test.py
Output
Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world
现在假设我们从另一个剧本中 将上述剧本称为:
脚本外部调用(_P).py
import test
print(test.apple)
test.hello_world()
print(test.__name__)
当你执行此操作时,
python external_calling.py
Output
42
I am inside hello_world
test
因此,以上不言自明地说明,当你们呼唤测试测试从另一个脚本, 如果循环__name__
内test.py
将不执行。