这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
当前回答
它是特殊的,当一个Python文件从命令线被召唤时,通常用来召唤一个“主()”函数或执行其他适当的启动代码,如命令线论点处理,例如。
它可以用多种方式写出来,另一个是:
def some_function_for_instance_main():
dosomething()
__name__ == '__main__' and some_function_for_instance_main()
我不是说你应该在生产代码中使用这一点,但它用来解释是否有“魔法”的东西。
它只是在Python文件中引用一个主要功能的条约。
其他回答
在 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
出口
Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world
现在假设我们从另一个脚本中称之为上面的脚本:
编辑 external_calling.py
import test
print(test.apple)
test.hello_world()
print(test.__name__)
当你执行这一点时,
python external_calling.py
出口
42
I am inside hello_world
test
因此,上述是自我解释的,当你从另一个脚本打电话测试时,如果在 test.py 中的 loop __name__ 不会执行。
要简要地说,你需要知道几点:
import a action actually runs all that can be run in a.py, meaning each line in a.py 因为第 1 点,你可能不希望一切都在 a.py 运行,当进口它 解决问题在第 2 点,Python 允许你使用一个条件检查 __name__ 是所有.py 模块中的暗示变量:
当 a.py 进口时, a.py 模块的 __name__ 的值设置为其文件名“a” 当 a.py 直接使用“python a.py” 运行时, __name__ 的值设置为 __main__ 字符串。
然后 python a.py 将运行部分 // 做 A 并进口一个将错过部分 // 做 A
如果 __name__ ==“__main__”意味着如果您正常运行 Python 文件如 python foo.py,则将特殊变量 __name__ 归分为“__main__”。
但是,如果您正在导入文件如“导入 foo”,则将 __name__ 归分为“foo”并且不会运行函数。
考虑一下:
if __name__ == "__main__":
main()
它检查Python脚本的 __name__属性是否是“__main__”。换句话说,如果程序本身执行,属性将是 __main__,因此程序将执行(在这种情况下,主()函数)。
但是,如果您的 Python 脚本是由一个模块使用的,任何代码外的,如果声明将执行,所以如果 __name__ ==“__main__”是用来检查程序是否作为一个模块使用,因此决定是否运行代码。
您可以通过这个简单的例子查看特殊变量 __name__:
创建 file1.py
if __name__ == "__main__":
print("file1 is being run directly")
else:
print("file1 is being imported")
创建 *file2.py
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")
执行 file2.py
出口:
file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly