__name__ ==“ __main__”怎么办?

Python

伽罗

2020-07-27

给定以下代码,该if __name__ == "__main__":怎么办?

# Threading example
import time, thread

def myfunction(string, sleeptime, lock, *args):
    while True:
        lock.acquire()
        time.sleep(sleeptime)
        lock.release()
        time.sleep(sleeptime)

if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

第4260篇《__name__ ==“ __main__”怎么办?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

11个回答
Stafan路易 2020.07.27

简而言之,就像C编程语言中main函数一样,它是运行文件的入口点

小小 2020.07.27

所有的答案都解释了功能。但是,我将提供其用法的一个示例,这可能有助于进一步澄清该概念。

假设您有两个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是运行的主文件),则仅执行代码。

别坑我 2020.07.27

如果此.py文件由其他.py文件导入,则“ if语句”下的代码将不会执行。

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

通常是为了测试而编写的。

伽罗 2020.07.27

python中的每个模块都有一个名为的属性__name____name__ attribute 的值__main__ 是直接运行模块时(例如)python my_module.py否则(如您说的那样import my_module)的值__name__ 是模块的名称。

简短说明一下小例子。

#Script test.py

apple = 42

def hello_world():
    print("I am inside hello_world")

if __name__ == "__main__":
    print("Value of __name__ is: ", __name__)
    print("Going to call hello_world")
    hello_world()

我们可以直接执行为

python test.py  

输出量

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

现在假设我们从其他脚本中调用上述脚本

#script external_calling.py

import test
print(test.apple)
test.hello_world()

print(test.__name__)

当你执行这个

python external_calling.py

输出量

42
I am inside hello_world
test

所以,以上是自我解释,当你调用其他脚本的测试,如果循环__name__test.py不会执行。

DavaidTony宝儿 2020.07.27

您可以使该文件可用作脚本以及可导入模块

fibo.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

小胖Gil 2020.07.27

考虑:

print __name__

上面的输出是__main__

if __name__ == "__main__":
  print "direct method"

上面的陈述是正确的,并显示“ direct method”假设他们在另一个类中导入了该类,则不会打印“直接方法”,因为在导入时会设置__name__ equal to "first model name"

番长 2020.07.27

的原因

if __name__ == "__main__":
    main()

主要是为了避免由于直接导入代码而导致的导入锁定问题如果要直接调用文件(这种情况),则要运行,但是如果导入了代码,则导入程序必须从真正的主模块输入代码,以避免导入锁定问题。main()__name__ == "__main__"

副作用是您自动登录支持多个入口点的方法。您可以使用main()作为入口点运行程序但不必如此虽然setup.py期望main(),但其他工具使用备用入口点。例如,要将文件作为gunicorn进程运行,请定义app()函数而不是main()与一样setup.pygunicorn导入您的代码,因此您不希望它在导入时执行任何操作(由于导入锁定问题)。

达蒙 2020.07.27

在本页的所有答案中,我都读了很多东西。我想说的是,如果您知道这件事,那么您肯定会理解这些答案,否则,您仍然会感到困惑。

简而言之,您需要了解以下几点:

  1. import aaction实际上会运行所有可以运行的内容a.py,这意味着其中的每一行a.py

  2. 由于第1点,您可能不希望在a.py导入时运行所有内容

  3. 为了解决第2点的问题,python允许您进行条件检查

  4. __name__是所有.py模块中的隐式变量a.py被导入,的值__name__a.py模块设置为它的文件名“ a“; a.py直接使用“ python a.py运行,的值__name__设置为字符串__main__

  5. 基于python如何__name__为每个模块设置变量的机制,您知道如何实现第3点吗?答案很简单,对吧?放置一个if条件:if __name__ == "__main__": // do A,然后python a.py运行该部分// do A,并import a跳过该部分“ // do A”;您甚至可以__name__ == "a"根据您的功能需求

python特殊的重要一点是第4点!其余只是基本逻辑。

Me无敌 2020.07.27

考虑:

if __name__ == "__main__":
    main()

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

但是,如果模块使用了Python脚本,if则将执行语句之外的任何代码,因此该代码if \__name__ == "\__main__"仅用于检查程序是否用作模块,从而决定是否运行该代码。

村村 2020.07.27

if __name__ == "__main__"是使用(例如)命令从(例如)命令行运行脚本时运行的部分python myscript.py

番长猴子 2020.07.27

通过将脚本作为命令传递给Python解释器来运行脚本时,

python myscript.py

缩进级别为0的所有代码都将执行。可以很好地定义已定义的函数和类,但是不会运行任何代码。与其他语言不同,没有任何main()函数可以自动运行-该main()函数隐式是顶层的所有代码。

在这种情况下,顶级代码是一个if块。 __name__是一个内置变量,其结果为当前模块的名称。但是,如果模块直接运行(如上myscript.py所示),则将__name__其设置为string "__main__"因此,您可以通过测试来测试您的脚本是直接运行还是通过其他方式导入

if __name__ == "__main__":
    ...

如果将脚本导入另一个模块,则将导入其各种功能和类定义,并执行其顶层代码,但上述if子句的then-body中的代码将不会运行,因为条件是没见过。作为一个基本示例,请考虑以下两个脚本:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")
# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

现在,如果您将解释器调用为

python one.py

输出将是

top-level in one.py
one.py is being run directly

如果two.py改为运行

python two.py

你得到

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

因此,在one加载模块时,其__name__等于"one"而不是"__main__"

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android