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

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

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


当前回答

要简要地说,你需要知道几点:

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__”:相当常见。

它检查一个模块是否正在进口。

换句话说,如果区块内部的代码只有当代码直接运行时才会执行。

让我们看看它使用一个简单的代码打印模块的名称:

# test.py
def test():
   print('test module name=%s' %(__name__))

if __name__ == '__main__':
   print('call test()')
   test()

如果我们通过 python test.py 直接运行代码,则模块名称为 __main__:

call test()
test module name=__main__

如果此.py 文件是由其他.py 文件进口的,则如果声明下的代码将不会被执行。

如果这个.py 是由 python 运行这个_py.py 在 Shell 下, 或在 Windows 中双击, 该代码在 if 声明 下将执行。

通常是用来测试的。

当您互动运行Python时,本地 __name__ 变量被分配为 __main__ 的值。 同样,当您从命令行中执行一个Python 模块时,而不是将其导入到另一个模块时,其 __name__ 属性被分配为 __main__ 的值,而不是模块的实际名称。

if __name__ == '__main__':
    # Do something appropriate here, like calling a
    # main() function defined elsewhere in this module.
    main()
else:
    # Do nothing. This module has been imported by another
    # module that wants to make use of the functions,
    # classes and other useful bits it has defined.

您可以将文件作为一个脚本以及一个可进口的模块使用。

fibo.py(一个名为fibo的模块)

# Other modules can IMPORT this MODULE to use the function fib
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

# This allows the file to be used as a SCRIPT
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

参考: https://docs.python.org/3.5/tutorial/modules.html

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

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

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

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

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