这样做做什么,为什么应该包括:if语句?

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

如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数main自动用作切入点,使用当我启动 Python 脚本时, 主函数为何不运行? 脚本从哪里开始运行 ?.


当前回答

我们看看__name__ == '__main__':经常

它检查一个模块是否正在导入 。

换言之,在if只有在代码直接运行时才执行此块。这里directly中指not imported.

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

# 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__

其他回答

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

Output

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

现在假设我们从另一个剧本中 将上述剧本称为:

脚本外部调用(_P).py

import test

print(test.apple)
test.hello_world()

print(test.__name__)

当你执行此操作时,

python external_calling.py

Output

42
I am inside hello_world
test

因此,以上不言自明地说明,当你们呼唤测试测试从另一个脚本, 如果循环__name__test.py将不执行。

if __name__ == "__main__":基本上是顶层的脚本环境, 它指定了翻译( “ 我最优先首先执行 ” ) 。

'__main__'是顶层代码执行范围的名称。模块的__name__设置为等于'__main__'从标准输入、脚本或交互式提示读取。

if __name__ == "__main__":
    # Execute only if run as a script
    main()

创建以下两个文件 :

# 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 设置globals()['__name__']和在b模块的模块到模块名称,b.


运行中python b.py:

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

仅在文件b.py已执行, Python 设置globals()['__name__']在此文件中的文件中"__main__"因此,if用于True这一次。

"如果"允许您选择使用 python 文件作为模块或脚本

  1. 如果(如果)名称名称名称名称名称=='主要`然后 python 文件被用作脚本 - 在这个语句下有逻辑值 。
  2. 如果名称名称名称名称名称 != '主要只有此 python 文件的函数/变量可用于其他 python 脚本enter image description here

Python 中每个模块都有特殊属性__name__的值。__name__属性设置为'__main__'当模块作为主程序执行时(例如运行中)python foo.py).

否则,__name__设置为被调用模块的名称。