这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
当前回答
让我们以更抽象的方式来看看答案:
假设我们有这个代码在x.py:
...
<Block A>
if __name__ == '__main__':
<Block B>
...
区块 A 和 B 运行,当我们运行 x.py。
但只有区块A(而不是B)运行,当我们运行另一个模块,例如 y.py,其中 x.py 被进口,代码从那里运行(就像在 x.py 的函数从 y.py 被称为时一样)。
其他回答
考虑一下:
print __name__
上面的结果是 __main__。
if __name__ == "__main__":
print "direct method"
上述声明是真实的,并打印“直接方法”。假设如果他们进口这个类别到另一个类别,它不会打印“直接方法”,因为在进口时,它将设置 __name__ 等于“第一型号名称”。
如果 __name__ ==“__main__”:该怎么办?
__name__ 是一个全球变量(在 Python 中,全球实际上意味着在模块层面)存在于所有名称空间。
作为唯一的特殊情况,但是,在任何Python过程你运行,如 mycode.py:
python mycode.py
否则匿名的全球名称空间将“__main__”的值归咎于其 __name__。
因此,包括最后的线条
if __name__ == '__main__':
main()
在您的 mycode.py 脚本的结尾,当它是由 Python 过程运行的主要输入点模块时,
将使您的脚本独特定义的主要功能运行。
使用此构造的另一个好处:您也可以将代码作为一个模块进口到另一个脚本,然后运行主功能,如果和当您的程序决定:
import mycode
# ... any amount of other code
mycode.main()
它是特殊的,当一个Python文件从命令线被召唤时,通常用来召唤一个“主()”函数或执行其他适当的启动代码,如命令线论点处理,例如。
它可以用多种方式写出来,另一个是:
def some_function_for_instance_main():
dosomething()
__name__ == '__main__' and some_function_for_instance_main()
我不是说你应该在生产代码中使用这一点,但它用来解释是否有“魔法”的东西。
它只是在Python文件中引用一个主要功能的条约。
您可以通过这个简单的例子查看特殊变量 __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
当您的脚本运行时,将其作为命令传递给Python翻译器时,
python myscript.py
定义的函数和类是定义的,好,但它们的代码没有运行。 与其他语言不同,没有主要()函数会自动运行 - 主要()函数是暗示所有代码在顶级。
在这种情况下,顶级代码是如果区块。 __name__ 是一个内置变量,以当前模块的名称进行评估. 但是,如果模块正在直接运行(如 myscript.py 上),则 __name__ 取代设置为“__main__”字符串。
if __name__ == "__main__":
...
如果您的脚本被导入到另一个模块,其各种功能和类定义将被导入,其顶级代码将被执行,但如果上述条款的后代代码不会运行,因为条件不满足。
# file 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")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
python one.py
产量将是
top-level in one.py
one.py is being run directly
如果您运行 two.py 而不是:
python 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