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

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

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


当前回答

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

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

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

其他回答

简言之,__name__是为每个脚本定义的变量,以定义脚本是作为主模块运行还是作为导入模块运行。

如果我们有两本脚本,

#script1.py
print "Script 1's name: {}".format(__name__)

#script2.py
import script1
print "Script 2's name: {}".format(__name__)

执行脚本1 的输出为

Script 1's name: __main__

执行脚本2 的输出为 :

Script1's name is script1
Script 2's name: __main__

如你所见__name__告诉我们哪个代码是“ main” 模块。 这很棒, 因为您可以只写代码, 而不必担心 C/ C++ 中的结构问题, 如果一个文件不执行“ main” 函数, 那么它无法编译为可执行文件, 如果它可以, 那么它就不能用作图书馆 。

说您会写出一个 Python 脚本,该脚本能做一些伟大的事情,而您会执行一系列用于其他目的的功能。如果我想使用这些功能,我可以在不执行您的程序的情况下导入并使用您的脚本(因为您的代码仅在if __name__ == "__main__":在 C/C++ 中,您需要将这些部分分割成一个单独的模块, 包括文件。 图片如下:

Complicated importing in C

箭头是导入链接。 对于试图包含前一个模块代码的3个模块,每个模块有6个文件(9个,计算执行文件)和5个链接。这使得将其他代码纳入 C 工程很难,除非它是专门编译成一个库。 现在为 Python 绘制它:

Elegant importing in Python

你写一个模块, 如果有人想使用你的代码, 他们只是导入它和__name__变量可以帮助将程序的可执行部分与库部分分开。

Python 中每个模块都有特殊属性__name__的值。__name__属性设置为'__main__'当模块作为主程序执行时(例如运行中)python foo.py).

否则,__name__设置为被调用模块的名称。

除了已经提供的资料外,if __name__ == "__main__":技术也是确保pytestunittest如果您不小心调用脚本, 脚本仍然在运行python代替pytest(或)python -m unittest举例来说:

def test_assert():
    assert 1 + 2 == 3

if __name__ == "__main__":
    import pytest
    pytest.main([__file__])

现在不管怎么称呼你的测试 都会在测试中进行pytestpython。在这里,这是unittest版本 :

import unittest

class Tests(unittest.TestCase):
    def test_assert(self):
        self.assertTrue(1 + 2 == 3)

if __name__ == "__main__":
    unittest.main()

然后您的脚本用python以一计号,以python -m unittest拨打。

现在,如果你也想确保 你所有的价码都通过pytest如果被召唤时python或者,如果你也想加入额外的参考物呢?

def test_assert():
    assert 1 + 2 == 3

if __name__ == "__main__":
    from pytest import main
    from sys import argv
    main([*argv, "-s"])

现在,你的python -v --html=report.html具有与pytest -v --html=report.html,等等。这是一个很好的方法,可以确保脚本仍然照原意运行, 即使没有按照预期运行pytestpython -m unittest电话

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

当您在本地交互运行 Python 时__name__变量的变量被指定值__main__同样,当您从命令行执行 Python 模块时,而不是将它导入到另一个模块中时,它__name__属性的属性被指定值__main__,而不是模块的实际名称。这样,模块可以查看自己的__name__用于确定它们是如何使用的值, 无论是作为对其它程序的支持还是作为从命令行执行的主要应用程序。 因此, 在 Python 模块中, 下列语系非常常见 :

if __name__ == '__main__':
    # Do something appropriate here, like calling a
    # main() function defined elsewhere in this module.
    main()
else:
    # Do nothing. This module has been imported by another
    # module that wants to make use of the functions,
    # classes and other useful bits it has defined.