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

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

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


当前回答

您可以查看特殊变量__name__使用此简单示例 :

创建创建文件1. py

if __name__ == "__main__":
    print("file1 is being run directly")
else:
    print("file1 is being imported")

创建 *file2。平平

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

执行文件2. py

Output:

file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly

其他回答

考虑:

if __name__ == "__main__":
    main()

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

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

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

我们看看__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__

当我们的模块中有某些语句时(M.py)我们想要当它作为主(而非导入)运行时被执行, 我们可以将这些语句( 测试案例、 打印语句) 置于此下if区块。

默认值( 当模块作为主模式运行时, 不导入)__name__变量设置为"__main__",当它将进口__name__变量将获得不同的值, 最有可能是模块的名称('M'这有助于将模块的不同变量合并运行,并区分其具体的输入和输出语句,以及如果有任何测试案例的话。

简简,使用此“if __name__ == "main"防止模块导入时运行(确定)代码的块。