这样做做什么,为什么应该包括:if
语句?
if __name__ == "__main__":
print("Hello, World!")
如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数main
自动用作切入点,使用当我启动 Python 脚本时, 主函数为何不运行? 脚本从哪里开始运行 ?.
只有你需要知道的事实
这个问题的其他答案太长了。 实际的机械非常简单,只有两个基本事实:
纯 Python 模块总是用变量创建__name__
设置为字符串"__main__"
.
导入模块的副作用是更改__name__
基本文件名的变量.py
扩展号。
如何使用这一信息
人们写作__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
将不执行。
您可以查看特殊变量__name__
使用此简单示例 :
创建创建文件1. py
if __name__ == "__main__":
print("file1 is being run directly")
else:
print("file1 is being imported")
创建 *file2。平平
import file1 as f1
print("__name__ from file1: {}".format(f1.__name__))
print("__name__ from file2: {}".format(__name__))
if __name__ == "__main__":
print("file2 is being run directly")
else:
print("file2 is being imported")
执行文件2. py
Output:
file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly