这是什么,为什么应该包括一个 if 声明?

if __name__ == "__main__":
    print("Hello, World!")

如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。


当前回答

当您的脚本运行时,将其作为命令传递给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

其他回答

如果 __name__ ==“__main__”是当脚本从(说)命令线运行时运行的部分,使用像 python myscript.py 这样的命令。

短答

它是字符串代码,保护用户在他们不打算时偶然提起脚本,这里有一些常见问题,当警卫被忽略了一个脚本:

长答

每当Python翻译器阅读源文件时,它都会做两件事:

让我们看看它是如何工作的,以及它是如何与您的问题有关的 __name__ 检查我们总是看到在 Python 脚本。

让我们使用一个稍微不同的代码样本来探索进口和脚本是如何工作的。

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

当您的模块是主要程序时

python foo.py

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

当您的模块由另一个模块进口时

# Suppose this is in some other main program.
import foo

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")

如果您的模块是主要程序,那么它会看到 __name__ 实际上设置为“__main__”并称为两个功能,打印线“函数 A”和“函数 B 10.0”。

只有当您的模块被另一个模块进口时

总是

它将在两种情况下打印“ __name__ 警卫”字符串。

总结

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

為什麼它會這樣工作?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      

# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")

# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")
    
print("before __name__ guard")
if __name__ == "__main__":
    bar()
print("after __name__ guard")

# XXX FIXME: useless (see below)
if __name__ == "__main__":
    n = int(input('Write a number: '))
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    print('Fibonacci number %i: %i' % (n, b))

n = int(input('Write a number: '))
a, b = 0, 1
while b < n:
    a, b = b, a+b
print('Fibonacci number %i: %i' % (n, b))

如果你想能够进口纤维,第一个版本是无用的,也是,因为有用的代码在一个部分,它不会运行,当你进口这个文件(在这种情况下 __name__ 不会是“__main__”). 正确的设计在这种情况下将是恢复代码,以便有用的部分在一个功能,你可以运行,当你想要之后你已经进口它。

def main():
    n = int(input('Write a number: '))
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    print('Fibonacci number %i: %i' % (n, b))

if __name__ == "__main__":
    main()

事实上,更好的设计仍然是将可重复使用的部分(实际计算)与用户可见的输入/输出隔离:

def fibn(n: int) -> int:
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    return b

def main() -> None:
    n = int(input('Write a number: '))
    print('Fibonacci number %i: %i' % (n, fibn(n)))

if __name__ == "__main__":
    main()

现在,您可以从 Fib 进口 Fibn 并从执行此进口的代码呼叫 Fibn() 函数。

def main():
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

if __name__ == "__main__":
    main()

(不同于类似于C的语言,主要名称对Python没有具体的含义;但它是常见的公约使用它作为将运行的东西的名称。

让我们以更抽象的方式来看看答案:

假设我们有这个代码在x.py:

...
<Block A>
if __name__ == '__main__':
    <Block B>
...

区块 A 和 B 运行,当我们运行 x.py。

但只有区块A(而不是B)运行,当我们运行另一个模块,例如 y.py,其中 x.py 被进口,代码从那里运行(就像在 x.py 的函数从 y.py 被称为时一样)。

在 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__ 不会执行。