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

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

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


当前回答

考虑:

print __name__

上述产出是__main__.

if __name__ == "__main__":
  print "direct method"

上述陈述属实,印有指纹“直接方法”假想他们是否将这门课 输入到另一门课上,它不会打印“直接方法”因为在进口时,它将设置__name__ equal to "first model name".

其他回答

这是 Java 程序员学习 Python 的答案。 每个 Java 文件通常包含一个公共课。 您可以以两种方式使用该课 :

  1. 从其他文件中给班级打个电话。 您只需在调用程序里导入它 。

  2. 单独运行班级 测试目的。

就后一种情况而言,该类应包含一种公共静态真空主主()方法。'__main__'.

if __name__ == "__main__":无法在导入文件时运行不需要的代码 。

例如,这是test1.pyif __name__ == "__main__"::

# "test1.py"

def hello()
    print("Hello")

hello()

还有test2.py进口test1.py:

# "test2.py"

import test1 # Here


然后,当奔跑的时候,test2.py, 1个Hello打印是因为不需要的代码hello()test1.py同时运行 :

python test2.py
Hello

当然,你可以打给test1.hello()test2.py:

# "test2.py"

import test1

test1.hello() # Here

然后,当奔跑的时候,test2, Hello已经打印 :

python test2.py
Hello
Hello

现在,添加if __name__ == "__main__":test1.py并放hello()在其之下:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()

这是test2.py:

# "test2.py"

import test1

test1.hello()

然后,当奔跑的时候,test2.py, 只有一个Hello打印是因为if __name__ == "__main__":防止要运行不需要的代码hello()何时test2.py进口进口进口test1.py:

python test2.py
Hello

此外,是否test1.py拥有if __name__ == "__main__":或非:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()
# "test1.py"

def hello()
    print("Hello")

hello()

一个Hello运行时正确打印test1.py:

python test1.py
Hello

考虑:

if __name__ == "__main__":
    main()

它检查是否__name__Python 脚本属性是"__main__"。换句话说,如果程序本身被执行,则属性将是__main__,因此程序将被执行(在这种情况下,main()职能)

然而,如果您的 Python 脚本被模块使用,if将执行语句,所以if __name__ == "__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这一次。

如果此. py 文件由其它. py 文件导入, 代码在if将不执行语句。

如果此. py 运行由python this_py.py在 shell 下方的代码,或在 Windows 中双击。if将执行语句。

通常写作用于测试。