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

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

如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数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

其他回答

下代码的代码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 中做.

您可以将文件作为脚本脚本脚本和(或)可导入可导入模块.

vibbo.py (一个称为模块的模块)fibo)

# Other modules can IMPORT this MODULE to use the function fib
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

# This allows the file to be used as a SCRIPT
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

参考:https://docs.python.org/3.5/tutorial/modules.html

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

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

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

假设我在维基百科上为网上剪贴写功能和课程。 当然,这也许不是一个好例子。

我想在另一个程序里使用这些函数 而不改写它

嗯,我进口了它们, 但是在文件的结尾,我放__name__ == '__main__'

当我们importa 模块,其中的所有代码都从开始到结束执行。但是当它达到条件时,它不会运行调乐曲 func, 复真2c2cfluc2等,这是维基百科__scrape__.

那么,在全球范围内,Python(Python)__name__定义为'__main__'用于当前程序 。

当我们import模块,它定义为当前程序和当前程序的名称空间中的变量。__name__'__main__':

文件文件文件测试.py

def func():
    # Do something
    pass

def func2():
    # Do something
    pass

print('The program name is set to ', globals()['__name__'])

if __name__=='__main__':
    # In the current program, __name__ is equal to '__main__'
    func('https://www.wikipedia.org')
    func2('https://www.wikipedia.org')
    # Or do more jobs

import test1
print('inside of current program')
print('name is current program', __name__)
print(globals()['test1'])
test1.func('another site')
test1.func2('another site')

Output

inside of test 1
name of program is set to test1
end of module
inside of current
__main__
<module 'test1' from 'C:\\users\\ir\\appdata\\local\\programs\\python\\python38\\lib\\test1.py'>

如果你是初学者 可能你现在唯一需要的答案就是此代码没有必要简单脚本的简单脚本。它只有在您想要能够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.)