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

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

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


当前回答

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

其他回答

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

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

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

如果 Python 口译员正在运行一个特定模块,那么__name__全局变量将拥有值"__main__":

def a():
    print("a")

def b():
    print("b")

if __name__ == "__main__":

        print ("you can see me")
        a()
else:

        print ("You can't see me")
        b()

当您运行此脚本时, 它会打印 :

you can see me
a

如果您导入此文件, 请说A要到文件的文件B,然后执行文件B时当时if __name__ == "__main__"文件中的文件A成为假假,所以它指纹:

You can't see me
b

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

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

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

简单的答案就是代码 代码是写在如果名称名称名称名称名称 == "主要":如果您在其它文件中导入的话, 将不会执行 。

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

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

通常写作用于测试。