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

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

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


当前回答

下代码的代码if __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'

请注意,只有最高层print()语中的语中my_test_module执行。


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

现在,如果你现在跑my_test_module.py作为 Python 脚本, 两者print()将执行语句:

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'

更全面的解释,可读作:什么是什么东西if __name__ == '__main__'在 Python 中做.

其他回答

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__':仅仅如果将模块作为脚本引用,则执行该模块。

例如,考虑以下模块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'

请注意,只有最高层print()语中的语中my_test_module执行。


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

现在,如果你现在跑my_test_module.py作为 Python 脚本, 两者print()将执行语句:

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'

更全面的解释,可读作:什么是什么东西if __name__ == '__main__'在 Python 中做.

创建文件,a.py , a.py , a.py , a.py , a.py , a.py , a.py , a.py:

print(__name__) # It will print out __main__

__name__始终等于__main__当该文件为直接直接运行显示此为主文件 。

创建另一个文件,b.py b.py,在同一目录中:

import a  # Prints a

运行它,它会打印a,即哪个文件的名称已导入.

所以,为了展示同一文件的两种不同行为,这是一个常用的把戏:

# Code to be run when imported into another python file

if __name__ == '__main__':
    # Code to be run only when run directly

当您的脚本作为命令传递给 Python 口译员时,

python myscript.py

缩进级别 0 的所有代码都得到执行。 定义的函数和类别是, 定义的, 定义明确, 但他们的代码没有运行 。 与其他语言不同, 没有main()函数自动运行 -main()函数是最高层所有代码的隐含值。

在这种情况下,最高层代码是if区块。__name__是一个内嵌变量。该变量对当前模块的名称进行评估。但是,如果模块直接运行,则该模块直接运行(如myscript.py above), then __name__而不是设置为字符串"__main__"因此,您可以测试您的脚本是直接运行的,还是通过测试输入其它东西的脚本。

if __name__ == "__main__":
    ...

如果您的脚本正在导入到另一个模块中, 它的各种函数和类定义将会导入, 并且它的顶层代码将会被执行, 但是在当时if以上条款将无法运行,因为不符合条件。作为一个基本例子,考虑以下两个脚本:

# 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

因此,当模块one装上子弹,装上子弹__name__等于相等"one"代替"__main__".

如果你是初学者 可能你现在唯一需要的答案就是此代码没有必要简单脚本的简单脚本。它只有在您想要能够import您的脚本 (或)unpickle等; 等; 参见关于其他一些非初始情景的其他答案 。

以略微不同的措辞,if __name__警卫是隐藏代码的机制, 用于隐藏其它代码 。 如果您没有特定的理由隐藏某些信息, 不要: 如果您不需要隐藏一些代码 。import,不要把它背后的警卫, 如果你这样做, 隐藏尽可能少的隐藏。

更详细一点,假设你有一个简单的脚本fib.py(改编回答本答案):

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

现在,如果你只是跑跑python fib.py效果不错,但是...__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))

现在,你不能import fib新版本的版本, 但如果你一开始不打算这样做, 这个版本其实更好, 因为它简单明了。

如果你(如果)do do do 做想要能够import fib,第一个版本也是没用的,因为有用的代码是在一个区域中,当您import此文件( 在哪个情况下)__name__将不为"__main__"))。在这种情况下,适当的设计将是重新设定代码,以便有用的部分在函数中发挥作用,在您想要运行时,可以运行importEd it. Ed. Ed it. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. Ed. 编辑。 编辑 编辑。 编辑。 编辑 编辑。 编辑。

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()

如果你现在import fib,呼吁main()将不会被执行;但当您运行时python fib.py会的

实际上,更好的设计仍然是将可重复使用部分(实际计算)与用户可看到的投入/产出分开:

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()

现在,你可以from fib import fibn然后喊叫,fibn()运行此功能的代码的函数import.

(我调用函数)fibn()只是为了让这个例子更清楚什么是这个例子。在现实生活中,你可以把它称为fib()并且确实from fib import fib.)

同样,你也可以import然后喊叫,main函数。

在回到问题中的代码时,我同样将代码从if功能中也包含一个功能,因此呼叫者如果愿意,可以援引该功能。

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()

这改变了lock变量;如果周围代码需要访问它,您需要将其global(或,也许,更好的是,重构mainreturn lock,并让调用者在自己的本地变量中捕捉到值。)

(不同于C类语言中的名称)mainPython 对 Python 没有具体意义; 但使用它作为将要运行的事物的名称, 是一个常见的公约 。 您仍然必须实际明确称呼它, 比如 :main(),不同于C.)