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

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

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


当前回答

当执行 Python 文件时, 它会创建许多特殊的变量, 例如__name__变量__name__您问题的答案是:

if __name__ == "__main__":
       # Do something

这意味着,如果所执行的文件的名称作为源文件运行,并且非模块然后它会运行里面的代码。 这可以用简单的示例来证明。 创建两个 Python 文件,foo.pysecond.py。然后在foo.py,类型如下:

if __name__ == "__main__":
       print("file is not imported")
else:
       print("file is imported")

和在second.py,类型如下:

import foo

if foo.__name__ == "__main__":
       print("file is not imported")
else:
       print("file is imported")

除此以外,如果你们要这样做,print(__name__)然后将打印__main__为什么?

因为文件以主要源代码,如果你愿意print(foo.__name__)将打印fuo fuo的默认值,因为__name__变量是文件的名称,默认是文件的默认名称,我的意思是,您也可以更改它。要做到这一点,只需去foo.py并做此操作的文件 :__name__ = "name"。然后当你运行文件,例如,

__name__ = "Hello, World!"
print(__name__)

然后产出将是:

Hello, World!

其他回答

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

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

您可以查看特殊变量__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

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

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

嗯,我进口了它们, 但是在文件的结尾,我放__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'>

所有答案都大致解释了它的功能。但我将举一个例子来说明它的用法,这可能有助于进一步澄清这个概念。

假设你有两个Python文件,A.py和B.py。a.py进口进口进口b.py。我们运行a.py文件, 在哪里import b.py代码先执行。在其余a.py代码运行,文件中的代码b.py必须完全运行。

在b.py 代码中,有一些代码是那个文件的独有代码b.py我们不想要任何其他文件(不包括b.py已导入 b. py 文件来运行 。

这就是这行代码检查。如果它是主文件(即,b.py运行代码,在这种情况下它不是代码 (a.py是正在运行的主文件),然后只有代码才能被执行。

让我们更抽象地看待答案:

假设我们有这个密码x.py:

...
<Block A>
if __name__ == '__main__':
    <Block B>
...

区块 A 和 B 正在运行时运行x.py.

但是,在我们运行另一个模块时,只运行A区块(而不是B区块),y.py例如,x.py导入并运行代码(例如当函数在x.py调自y.py).