这是什么,为什么应该包括一个 if 声明?

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

如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。


如果 __name__ ==“__main__”是当脚本从(说)命令线运行时运行的部分,使用像 python myscript.py 这样的命令。

短答

它是字符串代码,保护用户在他们不打算时偶然提起脚本,这里有一些常见问题,当警卫被忽略了一个脚本:

长答

每当Python翻译器阅读源文件时,它都会做两件事:

让我们看看它是如何工作的,以及它是如何与您的问题有关的 __name__ 检查我们总是看到在 Python 脚本。

让我们使用一个稍微不同的代码样本来探索进口和脚本是如何工作的。

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

当您的模块是主要程序时

python foo.py

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

当您的模块由另一个模块进口时

# Suppose this is in some other main program.
import foo

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")

如果您的模块是主要程序,那么它会看到 __name__ 实际上设置为“__main__”并称为两个功能,打印线“函数 A”和“函数 B 10.0”。

只有当您的模块被另一个模块进口时

总是

它将在两种情况下打印“ __name__ 警卫”字符串。

总结

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

為什麼它會這樣工作?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      

# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")

# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")
    
print("before __name__ guard")
if __name__ == "__main__":
    bar()
print("after __name__ guard")

当您的脚本运行时,将其作为命令传递给Python翻译器时,

python myscript.py

定义的函数和类是定义的,好,但它们的代码没有运行。 与其他语言不同,没有主要()函数会自动运行 - 主要()函数是暗示所有代码在顶级。

在这种情况下,顶级代码是如果区块。 __name__ 是一个内置变量,以当前模块的名称进行评估. 但是,如果模块正在直接运行(如 myscript.py 上),则 __name__ 取代设置为“__main__”字符串。

if __name__ == "__main__":
    ...

如果您的脚本被导入到另一个模块,其各种功能和类定义将被导入,其顶级代码将被执行,但如果上述条款的后代代码不会运行,因为条件不满足。

# 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

创建以下两个文件:

# a.py

import b
# b.py

print("__name__ equals " + __name__)

if __name__ == '__main__':
    print("if-statement was executed")

现在将每个文件单独运行。


使用 Python A.Py:

$ python a.py
__name__ equals b

当 a.py 运行时,它会导入 b 模块,这会导致 b 内部的所有代码运行。


运行Python b.py:

$ python b.py
__name__ equals __main__
if-statement was executed

当只执行 b.py 文件时,Python 在此文件中将 globals()['__name__'] 设置为 "__main__". 因此,如果声明评估为 True 这一次。

它是特殊的,当一个Python文件从命令线被召唤时,通常用来召唤一个“主()”函数或执行其他适当的启动代码,如命令线论点处理,例如。

它可以用多种方式写出来,另一个是:

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

我不是说你应该在生产代码中使用这一点,但它用来解释是否有“魔法”的东西。

它只是在Python文件中引用一个主要功能的条约。

当我们模块(M.py)中有某些声明时,我们希望当它作为主要(不进口)运行时,我们可以将这些声明(测试文件夹、印刷声明)置于此下,如果它被阻止。

默认情况下(当模块作为主运行时,不进口) __name__ 变量设置为“__main__”,当它被进口时, __name__ 变量将获得不同的值,最有可能是模块的名称(“M”)。

简而言之,使用这个“如果 __name__ ==“主””块,以防止(一定)代码在模块进口时运行。


开发和测试您的代码

def do_important():
    """This function does something very important"""

do_important()

以此为主,以此为主,以此为主。

~$ python important.py

问题

但是,如果你想将模块导入到另一个脚本:

import important

# do_important() # I must remember to uncomment to execute this!

更好的方式

if __name__ == "__main__":
    do_important()

但是,在这一点上,有一个皮托尼的改善方式。

如果我们想从模块之外运行这个业务过程,怎么办?

如果我们把我们想要练习的代码,当我们开发并测试这样的功能时,然后立即检查“__main__”之后:

def main():
    """business logic for when running this module as the primary one!"""
    setup()
    foo = do_important()
    bar = do_even_more_important(foo)
    for baz in bar:
        do_super_important(baz)
    teardown()

# Here's our payoff idiom!
if __name__ == '__main__':
    main()

我们现在有一个最终功能,我们的模块的结束将运行,如果我们运行模块作为主模块。

它将允许模块及其功能和类被进口到其他脚本,而不运行主功能,并将允许模块(及其功能和类)在从不同的“__main__”模块运行时被召唤,即。

import important
important.main()

当您互动运行Python时,本地 __name__ 变量被分配为 __main__ 的值。 同样,当您从命令行中执行一个Python 模块时,而不是将其导入到另一个模块时,其 __name__ 属性被分配为 __main__ 的值,而不是模块的实际名称。

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.

如果 __name__ ==“__main__”:该怎么办?

__name__ 是一个全球变量(在 Python 中,全球实际上意味着在模块层面)存在于所有名称空间。

作为唯一的特殊情况,但是,在任何Python过程你运行,如 mycode.py:

python mycode.py

否则匿名的全球名称空间将“__main__”的值归咎于其 __name__。

因此,包括最后的线条

if __name__ == '__main__':
    main()

在您的 mycode.py 脚本的结尾,当它是由 Python 过程运行的主要输入点模块时,

将使您的脚本独特定义的主要功能运行。

使用此构造的另一个好处:您也可以将代码作为一个模块进口到另一个脚本,然后运行主功能,如果和当您的程序决定:

import mycode
# ... any amount of other code
mycode.main()

让我们以更抽象的方式来看看答案:

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

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

区块 A 和 B 运行,当我们运行 x.py。

但只有区块A(而不是B)运行,当我们运行另一个模块,例如 y.py,其中 x.py 被进口,代码从那里运行(就像在 x.py 的函数从 y.py 被称为时一样)。

系统(Python 翻译器)为源文件(模块)提供的一些变量,您可以随时获得它们的值,所以,让我们专注于 __name__ 变量/属性:

如果 Python 将此源代码文件作为主程序(即您运行的文件),则将此文件的特殊 __name__ 变量设置为“__main__”值。

如果从另一个模块进口,则 __name__ 将设置到该模块的名称。

所以,在你的例子中,部分:

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))

这意味着代码区块:

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

希望这能帮出来。

如果 __name__ ==“__main__”:基本上是顶级脚本环境,并指定翻译者(‘我首先要执行的优先事项’)。

“__main__”是顶级代码执行范围的名称,当从标准输入、脚本或互动快点阅读时,模块的 __name__ 设置相当于“__main__”。

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

考虑一下:

print __name__

上面的结果是 __main__。

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

上述声明是真实的,并打印“直接方法”。假设如果他们进口这个类别到另一个类别,它不会打印“直接方法”,因为在进口时,它将设置 __name__ 等于“第一型号名称”。

接收“ab.py”文件:

def a():
    print('A function in ab file');
a()

import ab
def main():
    print('main function: this is where the action is')
def x():
    print ('peripheral task: might be useful in other projects')
x()
if __name__ == "__main__":
    main()

当您执行 xy.py 时,您将导入 ab. 导入声明立即在导入上运行模块,因此 ab 的操作在 xy 的剩余之前进行。

当你运行一个脚本 - 无论你命名什么 - 翻译者称之为“__main__”,使它成为主或“家”脚本,在运行一个外部脚本后返回。

下面的两行意味着:“如果这是“__main__”或“home”脚本,执行称为main()的函数”。这就是为什么你会看到一个 def main():锁上顶部,其中包含脚本的功能的主要流。

為什麼要實施這一點?

但代码在没有它的情况下工作。

如果我们有两本书,

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

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

此分類上一篇: Executing script1

Script 1's name: __main__

执行脚本2的结果是:

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

正如你可以看到的那样, __name__ 告诉我们哪个代码是“主要”模块,这是很好的,因为你只能写代码,并且不需要担心结构问题,如在 C/C++ 中,如果一个文件不执行一个“主要”函数,那么它不能作为一个可执行的编写,如果是这样,它不能用作图书馆。

箭头是进口链接. 对于三个模块,每个试图包含以前的模块代码,有六个文件(九个,计算实施文件)和五个链接. 这使得很难将其他代码纳入一个C项目,除非它是专门编写为图书馆。

此分類上一篇

我认为最好在深度和简单的词语中打破答案:

__name__: Python 中的每个模块都有一个特殊的属性,称为 __name__. 它是一个内置变量,返回模块的名称。

__main__:像其他编程语言一样,Python也有一个执行输入点,即主要的“__main__”是顶级代码执行范围的名称,基本上你有两种方式使用Python模块:直接运行它作为脚本,或者进口它。

因此,当模块作为主程序运行时, __name__ 属性的值设置为 __main__. 否则 __name__ 的值设置为包含模块名称。

您可以将文件作为一个脚本以及一个可进口的模块使用。

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

考虑一下:

if __name__ == "__main__":
    main()

它检查Python脚本的 __name__属性是否是“__main__”。换句话说,如果程序本身执行,属性将是 __main__,因此程序将执行(在这种情况下,主()函数)。

但是,如果您的 Python 脚本是由一个模块使用的,任何代码外的,如果声明将执行,所以如果 __name__ ==“__main__”是用来检查程序是否作为一个模块使用,因此决定是否运行代码。

原因为

if __name__ == "__main__":
    main()

首先要避免进口锁问题,即将直接输入代码,您想要主()运行,如果您的文件被直接提交(这是 __name__ ==“__main__”案例),但如果您的代码被进口,则进口商必须从真正的主要模块输入代码,以避免进口锁问题。

一个副作用是,你自动登录到一个方法,支持多个输入点. 你可以运行你的程序使用主要()作为输入点,但你不需要. 虽然 setup.py 等待主要(),其他工具使用替代输入点. 例如,运行你的文件作为一个 gunicorn 过程,你定义一个 app() 函数而不是一个主要()。

创建一个文件, a.py:

print(__name__) # It will print out __main__

__name__ 总是相当于 __main__ 每当此文件运行时,直接显示此文件是主要文件。

在同一目录中创建另一个文件,b.py:

import a  # Prints a

它将打印一个,即所进口的文件的名称。

因此,要显示相同文件的两个不同的行为,这是一个常用的技巧:

# Code to be run when imported into another python file

if __name__ == '__main__':
    # Code to be run only when run directly

什么是 __name__?

哪里

>>> print(__name__)
__main__
>>>

此分類上一篇:file.py:

print(__name__)

结果在 __main__

主持人.py:

def somefunction():
    print(__name__)

此分類上一篇:file.py:

import somefile
somefile.somefunction()

结果在Somefile

请注意,当在包或模块中使用时, __name__ 取出文件的名称. 实际模块或包路径的路径不被提供,但有自己的 DunderAlias __file__,这允许这样做。

>>> __name__ = 'Horrify' # Change default from __main__
>>> if __name__ == 'Horrify': print(__name__)
...
>>> else: print('Not Horrify')
...
Horrify
>>>

现在回答如果 __name__ ==“__main__”:

如果是包含代码块的流量控制声明,则将执行,如果所提供的值是真实的,我们已经看到 __name__ 可以采取 __main__ 或它已从中进口的文件名。

这告诉我们,如果运行文件是主要文件(或您正在直接从翻译器运行),那么该条件必须执行。

模块

变量

也可以用 __name__ 做其他,不太常见但有用的事情,我会在这里展示一些:

if __name__ != '__main__':
    # Do some useful things 

运行一个条件,如果文件是主一个和另一个,如果它不是

if __name__ == '__main__':
    # Execute something
else:
    # Do some useful things

我们看到是否 __name__ ==“__main__”:相当常见。

它检查一个模块是否正在进口。

换句话说,如果区块内部的代码只有当代码直接运行时才会执行。

让我们看看它使用一个简单的代码打印模块的名称:

# 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 文件, a.py 和 b.py. 现在, a.py 输入 b.py. 我们运行 a.py 文件,其中输入 b.py 代码首先执行。

在 b.py 代码中,有一些代码是专属于 b.py 文件,我们不希望任何其他文件(除了 b.py 文件),已进口了 b.py 文件,运行它。

如果它是主要文件(即,b.py)运行代码,在这种情况下它不是(a.py是主要文件运行),那么只有代码被执行。

如果此.py 文件是由其他.py 文件进口的,则如果声明下的代码将不会被执行。

如果这个.py 是由 python 运行这个_py.py 在 Shell 下, 或在 Windows 中双击, 该代码在 if 声明 下将执行。

通常是用来测试的。

要简要地说,你需要知道几点:

import a action actually runs all that can be run in a.py, meaning each line in a.py 因为第 1 点,你可能不希望一切都在 a.py 运行,当进口它 解决问题在第 2 点,Python 允许你使用一个条件检查 __name__ 是所有.py 模块中的暗示变量:

当 a.py 进口时, a.py 模块的 __name__ 的值设置为其文件名“a” 当 a.py 直接使用“python a.py” 运行时, __name__ 的值设置为 __main__ 字符串。

然后 python a.py 将运行部分 // 做 A 并进口一个将错过部分 // 做 A

这个答案是Java程序员学习Python. 每个Java文件通常包含一个公共类。

从其他文件中呼叫课堂. 你只需要将其进口到呼叫程序. 单独运行课堂站,用于测试目的。

对于后者来说,该类应该包含一个公共静态虚假主要()方法,在Python中,这个目的由全球定义的标签“__main__”提供。

简单地说,这是运行文件的输入点,就像C编程语言的主要功能一样。

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

一个小例子要简要解释。

脚本测试.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

现在假设我们从另一个脚本中称之为上面的脚本:

编辑 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

因此,上述是自我解释的,当你从另一个脚本打电话测试时,如果在 test.py 中的 loop __name__ 不会执行。

如果 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 文件,然后如果 __name__ == “__main__” 在 A 文件中变成错误,那么它打印:

You can't see me
b

您可以通过这个简单的例子查看特殊变量 __name__:

创建 file1.py

if __name__ == "__main__":
    print("file1 is being run directly")
else:
    print("file1 is being imported")

创建 *file2.py

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")

执行 file2.py

出口:

file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly

如果 __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'

请注意,仅在 my_test_module 中执行顶级印刷() 声明。


第二种可能性:将 my_test_module.py 作为脚本提交

现在,如果你将 my_test_module.py 作为 Python 脚本运行,那么打印() 陈述将运行:

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'

对于更全面的解释,您可以阅读在 Python 中做什么 __name__ == '__main__' 。

Python 主要功能是任何程序的起点. 当程序运行时,Python 翻译器连续运行代码. 主要功能只有当它作为 Python 程序运行时才运行。

def main():
    print("I am in the function")

print("I am out of the function")

当你运行脚本显示:

I am out of the function

而不是代码“我在职位”。

这是因为我们没有宣布呼叫函数“if__name__==“主”。

如果你使用它:

def main():
    print("I am in the function")

if __name__ == "__main__":
    main()

print("I am out of the function")

产量相当于

I am in the function
I am out of the function

在Python中,如果__name__==“__main__”允许您运行Python文件作为可重复使用的模块或单独的程序。

当Python 翻译器阅读源文件时,它将执行所有源文件中的代码;当Python 作为主程序运行“源文件”时,它设置了特殊变量 __name__ 以具有“__main__”值。

当您执行主函数时,它将读取如果声明,检查 __name__ 是否相当于 __main__。

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

否则, __name__ 的值将设置到它被召唤的模块的名称。

简单的说法:

下面看到的代码如果 __name__ ==“__main__”:只有当您的 Python 文件作为 python 示例1.py 执行时才会被召回。

但是,如果您想将您的 Python 文件 example1.py 作为一个模块来与另一个 Python 文件一起工作,请说 example2.py,下面的代码如果 __name__ ==“__main__”:不会运行或采取任何效果。

如果 __name__ ==“__main__”意味着如果您正常运行 Python 文件如 python foo.py,则将特殊变量 __name__ 归分为“__main__”。

但是,如果您正在导入文件如“导入 foo”,则将 __name__ 归分为“foo”并且不会运行函数。

当一个 Python 文件运行时,它创建了许多特殊变量,如 __name__. 变量 __name__ 保留了文件的名称。

if __name__ == "__main__":
       # Do something

这意味着,如果执行的文件的名称运行为源文件而不是模块,那么它将运行代码在其中。 这可以通过一个简单的例子证明。 创建两个 Python 文件, foo.py 和 second.py. 然后在 foo.py 中输入此:

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

在第二.py 中,输入此:

import foo

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

除此之外,如果你要做这个打印(__name__),那么它会打印 __main__。

因为文件是作为主要来源运行,如果你打印(foo.__name__)它将打印 foo 因为默认值的 __name__ 变量是文件的名称,默认情况下我意味着你也可以更改它。

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

然后,产量将是:

Hello, World!

当您执行模块(源文件)时,条件是否检查模块是否直接被召唤或从另一个源文件被召唤。

如果直接呼吁执行,则模块名称将设置为“主”,然后在如果区块内的代码将执行。

假设我在维基百科上写了网页扫描的功能和课程,当然,这可能不是一个好例子。

我想在另一个程序中使用这些功能,而不重写它。

好吧,我进口它们,但在该文件的结尾我把 __name__ == '__main__'

当我们进口一个模块时,它内部的所有代码都从开始到结束,但当它达到条件时,它不运行函数、函数2等,即维基百科 __scrape__。

好吧,在全球范围内,Python __name__ 为当前程序定义为“__main__”。

当我们进口一个模块时,它被定义为我们当前程序的名称空间中的变量,而当前程序 __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')

出口

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'>

# 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))

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))

如果你想能够进口纤维,第一个版本是无用的,也是,因为有用的代码在一个部分,它不会运行,当你进口这个文件(在这种情况下 __name__ 不会是“__main__”). 正确的设计在这种情况下将是恢复代码,以便有用的部分在一个功能,你可以运行,当你想要之后你已经进口它。

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()

事实上,更好的设计仍然是将可重复使用的部分(实际计算)与用户可见的输入/输出隔离:

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()

现在,您可以从 Fib 进口 Fibn 并从执行此进口的代码呼叫 Fibn() 函数。

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()

(不同于类似于C的语言,主要名称对Python没有具体的含义;但它是常见的公约使用它作为将运行的东西的名称。

简单的答案是下方写的代码,如果名称 ==“主”:如果您将其输入到另一个文件,则不会执行。

只有你需要知道的事实

实际的机械是相当简单的,只有两个基本事实:

纯 Python 模块总是用“__main__”字符串设置的变量 __name__ 创建。 导入一个模块具有改变 __name__ 变量的副作用,而无需.py 扩展。

如何使用此信息

人們寫 __name__ == '__main__' 以測試是否有一個模組已被輸入。

通常有某些代码不应该在进口时运行:测试代码,一次使用代码,命令线前端或网页服务器前端。

正如你可以从其他答案中看到的那样,人们似乎能够无限地谈论这个主题,但它确实是一个简单的事情,并且很容易掌握。

当您输入某种具有此条件的代码时,它将返回虚假(进口代码内),但将返回正确的代码将运行。

例如,这是 test1.py 没有如果 __name__ ==“__main__”::

# "test1.py"

def hello()
    print("Hello")

hello()

而且 test2.py 只輸入 test1.py:

# "test2.py"

import test1 # Here


然后,当运行 test2.py 时,一个 Hello 被打印,因为 test1.py 中的不需要的 hello() 代码也被运行:

python test2.py
Hello

当然,您可以在 test2.py 中拨打 test1.hello():

# "test2.py"

import test1

test1.hello() # Here

然后,当运行测试2时,印刷了两个Hello:

python test2.py
Hello
Hello

现在,添加如果 __name__ ==“__main__”:测试1.py 并将 hello() 放在下面:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()

此分類上一篇: Test2.py:

# "test2.py"

import test1

test1.hello()

然后,在运行 test2.py 时,只有一个 Hello 被打印,因为如果 __name__ ==“__main__”:在 test2.py 输入 test1.py 时阻止运行不需要的 hello() 代码:

python test2.py
Hello

此外, test1.py 是否有 __name__ == “__main__”: 或者不:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()
# "test1.py"

def hello()
    print("Hello")

hello()

One Hello 在运行 test1.py 时正确打印:

python test1.py
Hello

“如果”将允许您选择是否将Python文件作为模块或脚本

如果名称==‘主’ 然后 Python 文件是用作脚本 - 有逻辑在这个声明下,如果名称!=‘主’ 只有这个 Python 文件的功能/变量可以用在一些其他 Python 脚本

除了已经提供的信息,如果 __name__ ==“__main__”:技术也是一个很好的方式来确保您的最小和最单一的脚本仍然运行,如果你偶然用Python而不是Python(或Python -m最单一)。

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

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

import unittest

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

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

然后,你的脚本与 Python 呼叫相同,就像 Python -m 最单一的呼叫一样。

现在,如果你也想确保所有的麻烦被转移到问答,如果用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 等相同的效果,这是一个很好的方式来确保脚本仍然按照意图运行,即使不与预期的 pytest 或 python -m 最单一的通话运行。