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

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

如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么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 中,每个模块都有一个称为 __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__ 不会执行。

创建以下两个文件:

# a.py

import b
# b.py

print("__name__ equals " + __name__)

if __name__ == '__main__':
    print("if-statement was executed")

现在将每个文件单独运行。


使用 Python A.Py:

$ python a.py
__name__ equals b

当 a.py 运行时,它会导入 b 模块,这会导致 b 内部的所有代码运行。


运行Python b.py:

$ python b.py
__name__ equals __main__
if-statement was executed

当只执行 b.py 文件时,Python 在此文件中将 globals()['__name__'] 设置为 "__main__". 因此,如果声明评估为 True 这一次。

如果 __name__ == '__main__':下面的代码将仅执行,如果模块被称为脚本。

作为一个例子,请考虑以下模块 my_test_module.py:

# my_test_module.py

print('This is going to be printed out, no matter what')

if __name__ == '__main__':
    print('This is going to be printed out, only if user invokes the module as a script')

第一個選項:將 my_test_module.py 輸入到另一個模組

# main.py

import my_test_module

if __name__ == '__main__':
    print('Hello from main.py')

现在,如果你引用 main.py:

python main.py

>> 'This is going to be printed out, no matter what'
>> 'Hello from main.py'

请注意,仅在 my_test_module 中执行顶级印刷() 声明。


第二种可能性:将 my_test_module.py 作为脚本提交

现在,如果你将 my_test_module.py 作为 Python 脚本运行,那么打印() 陈述将运行:

python my_test_module.py

>>> 'This is going to be printed out, no matter what'
>>> 'This is going to be printed out, only if user invokes the module as a script'

对于更全面的解释,您可以阅读在 Python 中做什么 __name__ == '__main__' 。

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

“如果”将允许您选择是否将Python文件作为模块或脚本

如果名称==‘主’ 然后 Python 文件是用作脚本 - 有逻辑在这个声明下,如果名称!=‘主’ 只有这个 Python 文件的功能/变量可以用在一些其他 Python 脚本