标签归档:main

相当于Ruby中的`if __name__ ==’__main __’`

问题:相当于Ruby中的`if __name__ ==’__main __’`

我是Ruby的新手。我正在从包含要继续单独使用的工具的模块中导入函数。在Python中,我只需执行以下操作:

def a():
    ...
def b():
    ...
if __name__ == '__main__':
    a()
    b()

这使我可以运行程序或将其导入为模块使用a()和/或b()单独使用。Ruby中的等效范例是什么?

I am new to Ruby. I’m looking to import functions from a module that contains a tool I want to continue using separately. In Python I would simply do this:

def a():
    ...
def b():
    ...
if __name__ == '__main__':
    a()
    b()

This allows me to run the program or import it as a module to use a() and/or b() separately. What’s the equivalent paradigm in Ruby?


回答 0

从我在野外看到的Ruby(当然,不是一吨)来看,这不是标准的Ruby设计模式。模块和脚本应该保持独立,因此,如果没有真正好的清洁方法,我也不会感到惊讶。

编辑: 找到了。

if __FILE__ == $0
    foo()
    bar()
end

但这绝对不常见。

From the Ruby I’ve seen out in the wild (granted, not a ton), this is not a standard Ruby design pattern. Modules and scripts are supposed to stay separate, so I wouldn’t be surprised if there isn’t really a good, clean way of doing this.

EDIT: Found it.

if __FILE__ == $0
    foo()
    bar()
end

But it’s definitely not common.


回答 1

如果堆栈跟踪为空,我们可以从左右开始执行。我不知道这是常规使用还是非常规使用,因为我进入Ruby大约一周了。

if caller.length == 0
  # do stuff
end

概念证明:

文件:test.rb

#!/usr/bin/ruby                                                                 

if caller.length == 0
  puts "Main script"
end

puts "Test"

文件:shmest.rb

#!/usr/bin/ruby -I .                                                            

require 'test.rb'

puts "Shmest"

用法:

$ ./shmest.rb 
Test
Shmest

$ ./test.rb
Main script
Test

If stack trace is empty, we can start executing to the right and left. I don’t know if that’s used conventionally or unconventionally since I’m into Ruby for about a week.

if caller.length == 0
  # do stuff
end

Proof of concept:

file: test.rb

#!/usr/bin/ruby                                                                 

if caller.length == 0
  puts "Main script"
end

puts "Test"

file: shmest.rb

#!/usr/bin/ruby -I .                                                            

require 'test.rb'

puts "Shmest"

Usage:

$ ./shmest.rb 
Test
Shmest

$ ./test.rb
Main script
Test

回答 2

if $PROGRAM_NAME == __FILE__
  foo()
  bar()
end 

Rubocop首选:

if __FILE__ == $0
    foo()
    bar()
end
if $PROGRAM_NAME == __FILE__
  foo()
  bar()
end 

is preferred by Rubocop over this:

if __FILE__ == $0
    foo()
    bar()
end

__name__ ==“ __main__”是什么?

问题:__name__ ==“ __main__”是什么?

给定以下代码,该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))

Given the following code, what does the if __name__ == "__main__": do?

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

回答 0

每当Python解释器读取源文件时,它都会做两件事:

  • 它设置了一些特殊变量,例如__name__,然后

  • 它执行文件中找到的所有代码。

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

代码样例

让我们使用稍微不同的代码示例来探索导入和脚本的工作方式。假设以下文件位于foo.py

# Suppose this is foo.py.

print("before import")
import math

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

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

print("before __name__ guard")
if __name__ == '__main__':
    functionA()
    functionB()
print("after __name__ guard")

特殊变量

当Python交互程序读取源文件时,它首先定义一些特殊变量。在这种情况下,我们关心__name__变量。

当您的模块是主程序时

如果您将模块(源文件)作为主程序运行,例如

python foo.py

解释器将硬编码字符串赋值"__main__"__name__变量,即

# 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

解释器将搜索您的foo.py文件(以及搜索其他一些变体),并在执行该模块之前,它将"foo"导入语句中的名称分配给__name__变量,即

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

执行模块的代码

设置特殊变量后,解释器一次执行一次语句,执行模块中的所有代码。您可能想要在代码示例侧面打开另一个窗口,以便您可以按照以下说明进行操作。

总是

  1. 它打印字符串"before import"(不带引号)。

  2. 它将加载math模块并将其分配给名为的变量math。这等效于替换import math为以下内容(请注意,这__import__是Python中的低级函数,它接受字符串并触发实际的导入):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. 它输出字符串"before functionA"

  2. 它执行该def块,创建一个功能对象,然后将该功能对象分配给名为的变量functionA

  3. 它输出字符串"before functionB"

  4. 它执行第二个def块,创建另一个函数对象,然后将其分配给名为的变量functionB

  5. 它输出字符串"before __name__ guard"

仅当您的模块是主程序时

  1. 如果您的模块是主程序,那么它将看到__name__确实已将其设置为,"__main__"并且它将调用两个函数,分别输出字符串"Function A""Function B 10.0"

仅当您的模块由另一个导入时

  1. 相反)如果您的模块不是主程序,而是由另一个程序导入的,__name__则将为"foo",不是"__main__",它将跳过if语句的主体。

总是

  1. "after __name__ guard"在两种情况下都将打印字符串。

摘要

总而言之,这是两种情况下的打印内容:

# What gets printed if foo is the main program
before import
before functionA
before functionB
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 functionA
before functionB
before __name__ guard
after __name__ guard

为什么这样工作?

您自然会想知道为什么有人会想要这个。好吧,有时您想编写一个.py文件,该文件既可以被其他程序和/或模块用作模块,也可以作为主程序本身运行。例子:

  • 您的模块是一个库,但是您希望有一个脚本模式,在其中运行一些单元测试或演示。

  • 您的模块仅用作主程序,但是它具有一些单元测试,并且测试框架通过导入.py文件(如脚本)并运行特殊的测试功能来工作。您不希望它只是因为正在导入模块而尝试运行脚本。

  • 您的模块主要用作主程序,但它也为高级用户提供了程序员友好的API。

除了这些示例之外,可以优雅地用Python运行脚本只是设置一些魔术变量并导入脚本。“运行”脚本是导入脚本模块的副作用。

思想的食物

  • 问题:我可以有多个__name__检查块吗?答:这样做很奇怪,但是这种语言不会阻止您。

  • 假设以下内容在中foo2.py。如果python foo2.py在命令行上说会怎样?为什么?

# Suppose this is foo2.py.

def functionA():
    print("a1")
    from foo2 import functionB
    print("a2")
    functionB()
    print("a3")

def functionB():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    functionA()
    print("m2")
print("t2")
  • 现在,弄清楚如果删除__name__签入会发生什么foo3.py
# Suppose this is foo3.py.

def functionA():
    print("a1")
    from foo3 import functionB
    print("a2")
    functionB()
    print("a3")

def functionB():
    print("b")

print("t1")
print("m1")
functionA()
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")

Whenever the Python interpreter reads a source file, it does two things:

  • it sets a few special variables like __name__, and then

  • it executes all of the code found in the file.

Let’s see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.

Code Sample

Let’s use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.

# Suppose this is foo.py.

print("before import")
import math

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

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

print("before __name__ guard")
if __name__ == '__main__':
    functionA()
    functionB()
print("after __name__ guard")

Special Variables

When the Python interpeter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.

When Your Module Is the Main Program

If you are running your module (the source file) as the main program, e.g.

python foo.py

the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.

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

When Your Module Is Imported By Another

On the other hand, suppose some other module is the main program and it imports your module. This means there’s a statement like this in the main program, or in some other module the main program imports:

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

The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.

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

Executing the Module’s Code

After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.

Always

  1. It prints the string "before import" (without quotes).

  2. It loads the math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):

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

  2. It executes the def block, creating a function object, then assigning that function object to a variable called functionA.

  3. It prints the string "before functionB".

  4. It executes the second def block, creating another function object, then assigning it to a variable called functionB.

  5. It prints the string "before __name__ guard".

Only When Your Module Is the Main Program

  1. If your module is the main program, then it will see that __name__ was indeed set to "__main__" and it calls the two functions, printing the strings "Function A" and "Function B 10.0".

Only When Your Module Is Imported by Another

  1. (instead) If your module is not the main program but was imported by another one, then __name__ will be "foo", not "__main__", and it’ll skip the body of the if statement.

Always

  1. It will print the string "after __name__ guard" in both situations.

Summary

In summary, here’s what’d be printed in the two cases:

# What gets printed if foo is the main program
before import
before functionA
before functionB
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 functionA
before functionB
before __name__ guard
after __name__ guard

Why Does It Work This Way?

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don’t want it to try running the script just because it’s importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

Beyond those examples, it’s elegant that running a script in Python is just setting up a few magic variables and importing the script. “Running” the script is a side effect of importing the script’s module.

Food for Thought

  • Question: Can I have multiple __name__ checking blocks? Answer: it’s strange to do so, but the language won’t stop you.

  • Suppose the following is in foo2.py. What happens if you say python foo2.py on the command-line? Why?

# Suppose this is foo2.py.

def functionA():
    print("a1")
    from foo2 import functionB
    print("a2")
    functionB()
    print("a3")

def functionB():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    functionA()
    print("m2")
print("t2")
  • Now, figure out what will happen if you remove the __name__ check in foo3.py:
# Suppose this is foo3.py.

def functionA():
    print("a1")
    from foo3 import functionB
    print("a2")
    functionB()
    print("a3")

def functionB():
    print("b")

print("t1")
print("m1")
functionA()
print("m2")
print("t2")
  • What will this do when used as a script? When imported as a module?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")

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

回答 1

通过将脚本作为命令传递给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__"

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there’s no main() function that gets run automatically – the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won’t get run as the condition is not met. As a basic example, consider the following two scripts:

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

Now, if you invoke the interpreter as

python one.py

The output will be

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

If you run two.py instead:

python two.py

You get

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

Thus, when module one gets loaded, its __name__ equals "one" instead of "__main__".


回答 2

__name__变量(imho)的最简单解释如下:

创建以下文件。

# a.py
import b

# b.py
print "Hello World from %s!" % __name__

if __name__ == '__main__':
    print "Hello World again from %s!" % __name__

运行它们将为您提供以下输出:

$ python a.py
Hello World from b!

如您所见,导入模块时,Python globals()['__name__']在此模块中设置模块的名称。同样,在导入时,模块中的所有代码都在运行。由于if语句评估到False这一部分没有执行。

$ python b.py
Hello World from __main__!
Hello World again from __main__!

如您所见,执行文件时,Python globals()['__name__']在该文件中将设置为"__main__"。这次,该if语句求值True并正在运行。

The simplest explanation for the __name__ variable (imho) is the following:

Create the following files.

# a.py
import b

and

# b.py
print "Hello World from %s!" % __name__

if __name__ == '__main__':
    print "Hello World again from %s!" % __name__

Running them will get you this output:

$ python a.py
Hello World from b!

As you can see, when a module is imported, Python sets globals()['__name__'] in this module to the module’s name. Also, upon import all the code in the module is being run. As the if statement evaluates to False this part is not executed.

$ python b.py
Hello World from __main__!
Hello World again from __main__!

As you can see, when a file is executed, Python sets globals()['__name__'] in this file to "__main__". This time, the if statement evaluates to True and is being run.


回答 3

怎么if __name__ == "__main__":办?

概述基础知识:

  • __name__在作为程序入口点的模块中,全局变量为'__main__'。否则,这就是您导入模块的名称。

  • 因此,if仅当模块是程序的入口点时,该块下的代码才会运行。

  • 它允许模块中的代码可由其他模块导入,而无需在导入时执行下面的代码块。


我们为什么需要这个?

开发和测试您的代码

假设您正在编写旨在用作模块的Python脚本:

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

可以通过在底部添加此函数调用测试模块:

do_important()

并使用以下命令运行它(在命令提示符下):

~$ python important.py

问题

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

import important

在导入时,do_important将调用该函数,因此您可能会do_important()在底部注释掉函数调用。

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

然后,您必须记住是否已注释掉测试函数调用。这种额外的复杂性将意味着您可能会忘记,从而使您的开发过程更加麻烦。

更好的方法

__name__变量指向当前Python解释器所在的命名空间。

在导入的模块中,它是该模块的名称。

但是在主模块(或交互式Python会话,即解释器的Read,Eval,Print Loop或REPL)中,您正在运行其所有内容"__main__"

因此,如果您在执行之前进行检查:

if __name__ == "__main__":
    do_important()

有了以上内容,您的代码将仅在以主模块运行(或从另一个脚本有意调用)时执行。

更好的方法

不过,有一种Python方式可以对此进行改进。

如果我们想从模块外部运行该业务流程怎么办?

如果我们放上我们想在开发和测试这样的函数时使用的代码,然后在执行以下操作时'__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功能的情况下将该模块及其功能和类导入其他脚本,并且还将允许从其他'__main__'模块运行时调用该模块(及其功能和类),即

import important
important.main()

这个习语也可以在Python文档中的__main__模块说明中找到。该文本指出:

此模块表示解释程序的主程序在其中执行的(否则为匿名)范围-从标准输入,脚本文件或交互式提示中读取的命令。在这种环境中,惯用的“条件脚本”节使脚本运行:

if __name__ == '__main__':
    main()

What does the if __name__ == "__main__": do?

To outline the basics:

  • The global variable, __name__, in the module that is the entry point to your program, is '__main__'. Otherwise, it’s the name you import the module by.

  • So, code under the if block will only run if the module is the entry point to your program.

  • It allows the code in the module to be importable by other modules, without executing the code block beneath on import.


Why do we need this?

Developing and Testing Your Code

Say you’re writing a Python script designed to be used as a module:

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

You could test the module by adding this call of the function to the bottom:

do_important()

and running it (on a command prompt) with something like:

~$ python important.py

The Problem

However, if you want to import the module to another script:

import important

On import, the do_important function would be called, so you’d probably comment out your function call, do_important(), at the bottom.

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

And then you’ll have to remember whether or not you’ve commented out your test function call. And this extra complexity would mean you’re likely to forget, making your development process more troublesome.

A Better Way

The __name__ variable points to the namespace wherever the Python interpreter happens to be at the moment.

Inside an imported module, it’s the name of that module.

But inside the primary module (or an interactive Python session, i.e. the interpreter’s Read, Eval, Print Loop, or REPL) you are running everything from its "__main__".

So if you check before executing:

if __name__ == "__main__":
    do_important()

With the above, your code will only execute when you’re running it as the primary module (or intentionally call it from another script).

An Even Better Way

There’s a Pythonic way to improve on this, though.

What if we want to run this business process from outside the module?

If we put the code we want to exercise as we develop and test in a function like this and then do our check for '__main__' immediately after:

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

We now have a final function for the end of our module that will run if we run the module as the primary module.

It will allow the module and its functions and classes to be imported into other scripts without running the main function, and will also allow the module (and its functions and classes) to be called when running from a different '__main__' module, i.e.

import important
important.main()

This idiom can also be found in the Python documentation in an explanation of the __main__ module. That text states:

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:

if __name__ == '__main__':
    main()

回答 4

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

if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python myscript.py.


回答 5

怎么if __name__ == "__main__":办?

__name__是存在于所有命名空间中的全局变量(在Python中,global实际上是在模块级别上表示)。它通常是模块的名称(作为str类型)。

但是,作为唯一的特殊情况,无论您运行什么Python进程,如mycode.py:

python mycode.py

否则将匿名全局命名空间的值分配'__main__'__name__

因此,包括最后几行

if __name__ == '__main__':
    main()
  • 在mycode.py脚本的末尾,
  • 当它是由Python进程运行的主要入口点模块时,

将导致脚本的唯一定义main函数运行。

使用此构造的另一个好处:如果程序决定何时,还可以将代码作为模块导入另一个脚本中,然后运行main函数。

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

What does if __name__ == "__main__": do?

__name__ is a global variable (in Python, global actually means on the module level) that exists in all namespaces. It is typically the module’s name (as a str type).

As the only special case, however, in whatever Python process you run, as in mycode.py:

python mycode.py

the otherwise anonymous global namespace is assigned the value of '__main__' to its __name__.

Thus, including the final lines

if __name__ == '__main__':
    main()
  • at the end of your mycode.py script,
  • when it is the primary, entry-point module that is run by a Python process,

will cause your script’s uniquely defined main function to run.

Another benefit of using this construct: you can also import your code as a module in another script and then run the main function if and when your program decides:

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

回答 6

在这里,有关代码的“如何”的机制有很多不同之处,但是对我而言,直到我理解了“为什么”之后,才有意义。这对新程序员特别有用。

取得文件“ ab.py”:

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

还有第二个文件“ xy.py”:

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,你import ab。import语句在导入时立即运行模块,因此ab的操作要在的其余部分之前执行xy。完成后ab,继续xy

解释器会跟踪运行哪个脚本__name__。当您运行脚本时(无论您使用什么名称),解释器都会调用它"__main__",使其成为运行外部脚本后返回的主脚本或“主”脚本。

从该"__main__"脚本调用的任何其他脚本都被分配了其文件名作为其文件名__name__(例如__name__ == "ab.py")。因此,线if __name__ == "__main__":是解释程序的测试,以确定它是否正在解释/解析最初执行的“ home”脚本,或者它是否正在临时窥视另一个(外部)脚本。这使程序员可以灵活地让脚本在直接执行与在外部执行之间有所不同。

让我们逐步看一下上面的代码,以了解发生了什么,首先关注未缩进的行及其在脚本中出现的顺序。请记住,函数-或def-块在被调用之前不会自行执行任何操作。如果自言自语,口译员可能会说:

  • 打开xy.py作为“主”文件;"__main__"__name__变量中调用它。
  • 使用导入并打开文件__name__ == "ab.py"
  • 哦,有功能。我会记住的。
  • 好的,功能a();我才知道 打印’ ab文件中函数 ‘。
  • 文件结尾;回到"__main__"
  • 哦,有功能。我会记住的。
  • 另一个。
  • 功能x(); 好,打印“ 外围任务:可能在其他项目中有用 ”。
  • 这是什么?一个if声明。好了,条件已经满足(变量__name__已设置为"__main__"),所以我将输入main()函数并打印’ main函数:这是操作所在

最下面的两行表示:“如果这是"__main__"‘或’home’脚本,则执行名为main()“ 的功能。这就是为什么您会def main():在顶部看到一个块的原因,其中包含脚本功能的主要流程。

为什么要实施呢?

还记得我之前说的有关导入语句的内容吗?导入模块时,它不仅会“识别”它并等待进一步的指令-实际上会运行脚本中包含的所有可执行操作。因此,将脚本的内容main()有效地隔离到函数中,将其隔离,以便在被另一个脚本导入时不会立即运行。

同样,会有exceptions,但是通常的做法是main()通常不会在外部调用它。因此,您可能想知道又一件事:如果我们不调用main(),为什么还要调用脚本呢?这是因为许多人使用独立的函数来构造脚本,这些独立的函数旨在独立于文件中的其余代码运行。然后在脚本正文中的其他位置调用它们。这使我想到了这一点:

但是代码没有它就可以工作

恩,那就对了。可以从函数未包含的内联脚本中调用这些单独的main()函数。如果您习惯了(就像我在编程的早期学习阶段那样)构建可以完全满足您需要的内联脚本,并且如果您再次需要该操作,那么您将尝试再次找出它。嗯,您不习惯这种代码的内部结构,因为它的构建更加复杂并且阅读起来也不那么直观。

但这是一个脚本,可能无法从外部调用其功能,因为如果执行该脚本,它将立即开始计算和分配变量。而且,如果您想重用某个功能,则新脚本与旧脚本的关联性可能会很高,以至于变量会冲突。

在拆分独立功能时,您可以通过将其调用到另一个脚本中来重用以前的工作。例如,“ example.py”可能会导入“ xy.py”并调用x(),从而利用“ xy.py” 中的“ x”功能。(也许是将给定文本字符串的第三个单词大写;从数字列表中创建一个NumPy数组并对其进行平方;或者对3D表面进行趋势处理。这种可能性是无限的。)

(顺便说一句,这个问题包含@kindall的答案,它最终帮助我理解了-原因,而不是方法。不幸的是,它被标记为与副本的副本,我认为这是错误的。)

There are lots of different takes here on the mechanics of the code in question, the “How”, but for me none of it made sense until I understood the “Why”. This should be especially helpful for new programmers.

Take file “ab.py”:

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

And a second file “xy.py”:

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

What is this code actually doing?

When you execute xy.py, you import ab. The import statement runs the module immediately on import, so ab‘s operations get executed before the remainder of xy‘s. Once finished with ab, it continues with xy.

The interpreter keeps track of which scripts are running with __name__. When you run a script – no matter what you’ve named it – the interpreter calls it "__main__", making it the master or ‘home’ script that gets returned to after running an external script.

Any other script that’s called from this "__main__" script is assigned its filename as its __name__ (e.g., __name__ == "ab.py"). Hence, the line if __name__ == "__main__": is the interpreter’s test to determine if it’s interpreting/parsing the ‘home’ script that was initially executed, or if it’s temporarily peeking into another (external) script. This gives the programmer flexibility to have the script behave differently if it’s executed directly vs. called externally.

Let’s step through the above code to understand what’s happening, focusing first on the unindented lines and the order they appear in the scripts. Remember that function – or def – blocks don’t do anything by themselves until they’re called. What the interpreter might say if mumbled to itself:

  • Open xy.py as the ‘home’ file; call it "__main__" in the __name__ variable.
  • Import and open file with the __name__ == "ab.py".
  • Oh, a function. I’ll remember that.
  • Ok, function a(); I just learned that. Printing ‘A function in ab file‘.
  • End of file; back to "__main__"!
  • Oh, a function. I’ll remember that.
  • Another one.
  • Function x(); ok, printing ‘peripheral task: might be useful in other projects‘.
  • What’s this? An if statement. Well, the condition has been met (the variable __name__ has been set to "__main__"), so I’ll enter the main() function and print ‘main function: this is where the action is‘.

The bottom two lines mean: “If this is the "__main__" or ‘home’ script, execute the function called main()“. That’s why you’ll see a def main(): block up top, which contains the main flow of the script’s functionality.

Why implement this?

Remember what I said earlier about import statements? When you import a module it doesn’t just ‘recognize’ it and wait for further instructions – it actually runs all the executable operations contained within the script. So, putting the meat of your script into the main() function effectively quarantines it, putting it in isolation so that it won’t immediately run when imported by another script.

Again, there will be exceptions, but common practice is that main() doesn’t usually get called externally. So you may be wondering one more thing: if we’re not calling main(), why are we calling the script at all? It’s because many people structure their scripts with standalone functions that are built to be run independent of the rest of the code in the file. They’re then later called somewhere else in the body of the script. Which brings me to this:

But the code works without it

Yes, that’s right. These separate functions can be called from an in-line script that’s not contained inside a main() function. If you’re accustomed (as I am, in my early learning stages of programming) to building in-line scripts that do exactly what you need, and you’ll try to figure it out again if you ever need that operation again … well, you’re not used to this kind of internal structure to your code, because it’s more complicated to build and it’s not as intuitive to read.

But that’s a script that probably can’t have its functions called externally, because if it did it would immediately start calculating and assigning variables. And chances are if you’re trying to re-use a function, your new script is related closely enough to the old one that there will be conflicting variables.

In splitting out independent functions, you gain the ability to re-use your previous work by calling them into another script. For example, “example.py” might import “xy.py” and call x(), making use of the ‘x’ function from “xy.py”. (Maybe it’s capitalizing the third word of a given text string; creating a NumPy array from a list of numbers and squaring them; or detrending a 3D surface. The possibilities are limitless.)

(As an aside, this question contains an answer by @kindall that finally helped me to understand – the why, not the how. Unfortunately it’s been marked as a duplicate of this one, which I think is a mistake.)


回答 7

当我们的模块(M.py)中有某些语句时,我们希望在将其作为main(而不是导入)运行时执行该语句,我们可以将这些语句(测试用例,打印语句)放在此if块下。

默认情况下(当模块作为主模块运行而不是导入时),该__name__变量设置为"__main__",导入时,该__name__变量将获得一个不同的值,很可能是模块的名称('M')。这有助于一起运行模块的不同变体,分离其特定的输入和输出语句,以及是否存在测试用例。

简而言之,使用此’ if __name__ == "main"‘块可防止在导入模块时运行(某些)代码。

When there are certain statements in our module (M.py) we want to be executed when it’ll be running as main (not imported), we can place those statements (test-cases, print statements) under this if block.

As by default (when module running as main, not imported) the __name__ variable is set to "__main__", and when it’ll be imported the __name__ variable will get a different value, most probably the name of the module ('M'). This is helpful in running different variants of a modules together, and separating their specific input & output statements and also if there are any test-cases.

In short, use this ‘if __name__ == "main" ‘ block to prevent (certain) code from being run when the module is imported.


回答 8

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

因此,如果我们有两个脚本;

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

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

执行script1的输出是

Script 1's name: __main__

执行script2的输出是:

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

如你看到的, __name__告诉我们哪个代码是“主”模块。这很棒,因为您可以编写代码,而不必担心C / C ++中的结构性问题,在这种情况下,如果文件未实现“ main”功能,则无法将其编译为可执行文件,如果可以,然后它不能用作库。

假设您编写的Python脚本功能出色,并实现了许多对其他用途有用的功能。如果要使用它们,我可以导入您的脚本并使用它们而无需执行您的程序(假设您的代码仅在if __name__ == "__main__":上下文中执行 )。而在C / C ++中,您将必须将这些部分分成一个单独的模块,然后再包含文件。如下图所示;

箭头是导入链接。对于三个试图包含先前模块代码的模块,有六个文件(九个,计算实现文件)和五个链接。除非将其专门编译为库,否则很难将其他代码包含到C项目中。现在将其描述为适用于Python:

您编写了一个模块,如果有人想使用您的代码,他们只需将其导入即可,并且__name__变量可以帮助将程序的可执行部分与库部分分开。

Put simply, __name__ is a variable defined for each script that defines whether the script is being run as the main module or it is being run as an imported module.

So if we have two scripts;

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

and

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

The output from executing script1 is

Script 1's name: __main__

And the output from executing script2 is:

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

As you can see, __name__ tells us which code is the ‘main’ module. This is great, because you can just write code and not have to worry about structural issues like in C/C++, where, if a file does not implement a ‘main’ function then it cannot be compiled as an executable and if it does, it cannot then be used as a library.

Say you write a Python script that does something great and you implement a boatload of functions that are useful for other purposes. If I want to use them I can just import your script and use them without executing your program (given that your code only executes within the if __name__ == "__main__": context). Whereas in C/C++ you would have to portion out those pieces into a separate module that then includes the file. Picture the situation below;

The arrows are import links. For three modules each trying to include the previous modules code there are six files (nine, counting the implementation files) and five links. This makes it difficult to include other code into a C project unless it is compiled specifically as a library. Now picture it for Python:

You write a module, and if someone wants to use your code they just import it and the __name__ variable can help to separate the executable portion of the program from the library part.


回答 9

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

假设我们在以下代码中x.py

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

块A和B,当我们正在运行的运行x.py

但是,y.py例如,当我们运行另一个模块时,仅运行块A(而不运行B),例如,在其中x.py导入了代码并从那里运行代码(例如,当x.py从中调用in函数时y.py)。

Let’s look at the answer in a more abstract way:

Suppose we have this code in x.py:

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

Blocks A and B are run when we are running x.py.

But just block A (and not B) is run when we are running another module, y.py for example, in which x.py is imported and the code is run from there (like when a function in x.py is called from y.py).


回答 10

交互式运行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.

When you run Python interactively the local __name__ variable is assigned a value of __main__. Likewise, when you execute a Python module from the command line, rather than importing it into another module, its __name__ attribute is assigned a value of __main__, rather than the actual name of the module. In this way, modules can look at their own __name__ value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line. Thus, the following idiom is quite common in Python modules:

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.

回答 11

考虑:

if __name__ == "__main__":
    main()

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

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

Consider:

if __name__ == "__main__":
    main()

It checks if the __name__ attribute of the Python script is "__main__". In other words, if the program itself is executed, the attribute will be __main__, so the program will be executed (in this case the main() function).

However, if your Python script is used by a module, any code outside of the if statement will be executed, so if \__name__ == "\__main__" is used just to check if the program is used as a module or not, and therefore decides whether to run the code.


回答 12

在解释任何有关if __name__ == '__main__'它的内容之前,重要的是要了解它是什么__name__以及它做什么。

什么__name__

__name__DunderAlias-可以认为是全局变量(可从模块访问),并且与相似global

它是type(__name__)(yielding <class 'str'>)指示的字符串(如上所述),并且是Python 3Python 2版本的内置标准。

哪里:

它不仅可以在脚本中使用,而且可以在解释器和模块/包中找到。

口译员:

>>> print(__name__)
__main__
>>>

脚本:

test_file.py

print(__name__)

导致 __main__

模块或包装:

somefile.py:

def somefunction():
    print(__name__)

test_file.py:

import somefile
somefile.somefunction()

导致 somefile

请注意,在包或模块中使用时,使用__name__文件名。没有给出实际模块或包路径的路径,但是具有自己的DunderAlias__file__,因此可以这一点。

您应该看到,where __name__,它总是在其中返回主文件(或程序)__main__,并且如果它是一个模块/程序包,或者正在运行其他Python脚本的任何东西,则将在其中返回文件名。起源于。

实践:

作为变量意味着它的值可以被覆盖(“可以”并不意味着“应该”),覆盖的值__name__将导致缺乏可读性。因此,无论出于任何原因都不要这样做。如果您需要一个变量,请定义一个新变量。

始终假定__name__为be 的值__main__或文件名。再次更改此默认值将引起更多混乱,这会带来好处,并进一步导致问题。

例:

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

通常,将if __name__ == '__main__'in 包含在脚本中被认为是一种好习惯。

现在回答if __name__ == '__main__'

现在我们知道__name__事物的行为变得更加清晰:

一个if是包含的代码块,如果给定的值是true,将执行流控制语句。我们已经看到这__name__可以采取
__main__导入的文件名导入的文件名。

这意味着,如果__name__等于,__main__则该文件必须是主文件并且必须实际上正在运行(或者它是解释器),而不是导入脚本的模块或包。

如果确实__name__采用了值,__main__那么该代码块中的所有内容都将执行。

这告诉我们,如果正在运行的文件是主文件(或者直接从解释器运行),则必须执行该条件。如果它是一个包,则不应该,并且值不应该是__main__

模块:

__name__ 也可以在模块中使用以定义模块名称

变体:

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

仅当文件是模块或软件包时才执行:

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

如果文件是主文件,则运行一个条件,如果文件不是主文件,则运行另一个条件:

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

您也可以使用它在软件包和模块上提供可运行的帮助功能/实用程序,而无需精心使用库。

它还允许模块作为主脚本从命令行运行,这也非常有用。

Before explaining anything about if __name__ == '__main__' it is important to understand what __name__ is and what it does.

What is __name__?

__name__ is a DunderAlias – can be thought of as a global variable (accessible from modules) and works in a similar way to global.

It is a string (global as mentioned above) as indicated by type(__name__) (yielding <class 'str'>), and is an inbuilt standard for both Python 3 and Python 2 versions.

Where:

It can not only be used in scripts but can also be found in both the interpreter and modules/packages.

Interpreter:

>>> print(__name__)
__main__
>>>

Script:

test_file.py:

print(__name__)

Resulting in __main__

Module or package:

somefile.py:

def somefunction():
    print(__name__)

test_file.py:

import somefile
somefile.somefunction()

Resulting in somefile

Notice that when used in a package or module, __name__ takes the name of the file. The path of the actual module or package path is not given, but has its own DunderAlias __file__, that allows for this.

You should see that, where __name__, where it is the main file (or program) will always return __main__, and if it is a module/package, or anything that is running off some other Python script, will return the name of the file where it has originated from.

Practice:

Being a variable means that it’s value can be overwritten (“can” does not mean “should”), overwriting the value of __name__ will result in a lack of readability. So do not do it, for any reason. If you need a variable define a new variable.

It is always assumed that the value of __name__ to be __main__ or the name of the file. Once again changing this default value will cause more confusion that it will do good, causing problems further down the line.

example:

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

It is considered good practice in general to include the if __name__ == '__main__' in scripts.

Now to answer if __name__ == '__main__':

Now we know the behaviour of __name__ things become clearer:

An if is a flow control statement that contains the block of code will execute if the value given is true. We have seen that __name__ can take either __main__ or the file name it has been imported from.

This means that if __name__ is equal to __main__ then the file must be the main file and must actually be running (or it is the interpreter), not a module or package imported into the script.

If indeed __name__ does take the value of __main__ then whatever is in that block of code will execute.

This tells us that if the file running is the main file (or you are running from the interpreter directly) then that condition must execute. If it is a package then it should not, and the value will not be __main__.

Modules:

__name__ can also be used in modules to define the name of a module

Variants:

It is also possible to do other, less common but useful things with __name__, some I will show here:

Executing only if the file is a module or package:

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

Running one condition if the file is the main one and another if it is not:

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

You can also use it to provide runnable help functions/utilities on packages and modules without the elaborate use of libraries.

It also allows modules to be run from the command line as main scripts, which can be also very useful.


回答 13

我认为最好是深入浅出的答案:

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

__main__:与其他编程语言一样,Python也具有执行入口点,即main。'__main__' 是执行顶级代码的作用域的名称。基本上,您有两种使用Python模块的方式:直接将其作为脚本运行,或将其导入。当模块作为脚本运行时,其__name__设置为__main__

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

I think it’s best to break the answer in depth and in simple words:

__name__: Every module in Python has a special attribute called __name__. It is a built-in variable that returns the name of the module.

__main__: Like other programming languages, Python too has an execution entry point, i.e., main. '__main__' is the name of the scope in which top-level code executes. Basically you have two ways of using a Python module: Run it directly as a script, or import it. When a module is run as a script, its __name__ is set to __main__.

Thus, the value of the __name__ attribute is set to __main__ when the module is run as the main program. Otherwise the value of __name__ is set to contain the name of the module.


回答 14

这是从命令行调用Python文件时的特殊功能。通常用于调用“ main()”函数或执行其他适当的启动代码,例如命令行参数处理。

它可以用几种方式编写。另一个是:

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

我并不是说您应该在生产代码中使用它,但是它可以说明没有什么“魔术” if __name__ == '__main__'。在Python文件中调用主函数是一个很好的约定。

It is a special for when a Python file is called from the command line. This is typically used to call a “main()” function or execute other appropriate startup code, like commandline arguments handling for instance.

It could be written in several ways. Another is:

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

I am not saying you should use this in production code, but it serves to illustrate that there is nothing “magical” about if __name__ == '__main__'. It is a good convention for invoking a main function in Python files.


回答 15

系统(Python解释器)为源文件(模块)提供了许多变量。您可以随时获取它们的值,因此,让我们关注__name__变量/属性:

当Python加载源代码文件时,它将执行在其中找到的所有代码。(请注意,它不会调用文件中定义的所有方法和函数,但会定义它们。)

但是,在解释器执行源代码文件之前,它会为该文件定义一些特殊的变量。__名称__是Python为每个源代码文件自动定义的那些特殊变量之一。

如果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 ”。

希望这会有所帮助。

There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the __name__ variable/attribute:

When Python loads a source code file, it executes all of the code found in it. (Note that it doesn’t call all of the methods and functions defined in the file, but it does define them.)

Before the interpreter executes the source code file though, it defines a few special variables for that file; __name__ is one of those special variables that Python automatically defines for each source code file.

If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special __name__ variable for this file to have a value “__main__”.

If this is being imported from another module, __name__ will be set to that module’s name.

So, in your example in part:

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

means that the code block:

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

will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of __name__ will not equal to “main” in that particular instance.

Hope this helps out.


回答 16

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

'__main__'是执行顶级代码的作用域的名称。从标准输入,脚本或交互式提示中读取时,模块的__name__设置等于'__main__'

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

if __name__ == "__main__": is basically the top-level script environment, and it specifies the interpreter that (‘I have the highest priority to be executed first’).

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

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

回答 17

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

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

  1. import a 操作实际上会运行所有可以在“ a”中运行的内容

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

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

  4. __name__是所有.py模块中的隐式变量;当a.py被导入,的值__name__a.py模块设置为它的文件名“ a“; 当a.py直接使用运行“ python a.py”,该装置a.py在所述入口点,则该值__name__a.py模块被设置为一个字符串__main__

  5. 基于python如何__name__为每个模块设置变量的机制,您知道如何实现第3点吗?答案很简单,对吧?把一个if条件:if __name__ == "__main__": ...; 您甚至可以__name__ == "a"根据您的功能需求放

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

I’ve been reading so much throughout the answers on this page. I would say, if you know the thing, for sure you will understand those answers, otherwise, you are still confused.

To be short, you need to know several points:

  1. import a action actually runs all that can be ran in “a”

  2. Because of point 1, you may not want everything to be run in “a” when importing it

  3. To solve the problem in point 2, python allows you to put a condition check

  4. __name__ is an implicit variable in all .py modules; when a.py is imported, the value of __name__ of a.py module is set to its file name “a“; when a.py is run directly using “python a.py“, which means a.py is the entry point, then the value of __name__ of a.py module is set to a string __main__

  5. Based on the mechanism how python sets the variable __name__ for each module, do you know how to achieve point 3? The answer is fairly easy, right? Put a if condition: if __name__ == "__main__": ...; you can even put if __name__ == "a" depending on your functional need

The important thing that python is special at is point 4! The rest is just basic logic.


回答 18

考虑:

print __name__

上面的输出是__main__

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

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

Consider:

print __name__

The output for the above is __main__.

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

The above statement is true and prints “direct method”. Suppose if they imported this class in another class it doesn’t print “direct method” because, while importing, it will set __name__ equal to "first model name".


回答 19

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

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

You can make the file usable as a script as well as an importable module.

fibo.py (a module named 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]))

Reference: https://docs.python.org/3.5/tutorial/modules.html


回答 20

的原因

if __name__ == "__main__":
    main()

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

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

The reason for

if __name__ == "__main__":
    main()

is primarily to avoid the import lock problems that would arise from having code directly imported. You want main() to run if your file was directly invoked (that’s the __name__ == "__main__" case), but if your code was imported then the importer has to enter your code from the true main module to avoid import lock problems.

A side-effect is that you automatically sign on to a methodology that supports multiple entry points. You can run your program using main() as the entry point, but you don’t have to. While setup.py expects main(), other tools use alternate entry points. For example, to run your file as a gunicorn process, you define an app() function instead of a main(). Just as with setup.py, gunicorn imports your code so you don’t want it do do anything while it’s being imported (because of the import lock issue).


回答 21

该答案适用于学习Python的Java程序员。每个Java文件通常包含一个公共类。您可以通过两种方式使用该类:

  1. 从其他文件调用类。您只需要将其导入调用程序中即可。

  2. 出于测试目的,单独运行类。

对于后一种情况,该类应包含一个公共的静态void main()方法。在Python中,此目的由全局定义的标签实现'__main__'

This answer is for Java programmers learning Python. Every Java file typically contains one public class. You can use that class in two ways:

  1. Call the class from other files. You just have to import it in the calling program.

  2. Run the class stand alone, for testing purposes.

For the latter case, the class should contain a public static void main() method. In Python this purpose is served by the globally defined label '__main__'.


回答 22

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

请注意,仅执行print()in中的顶级语句my_test_module


第二种可能性:my_test_module.py作为脚本调用

现在,如果您my_test_module.py以Python脚本运行,则两个print()语句都将执行:

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'

The code under if __name__ == '__main__': will only be executed if the module is invoked as a script.

As an example consider the following module 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')

1st possibility: Import my_test_module.py in another module

# main.py

import my_test_module

if __name__ == '__main__':
    print('Hello from main.py')

Now if you invoke main.py:

python main.py 

>> 'This is going to be printed out, no matter what'
>> 'Hello from main.py'

Note that only the top-level print() statement in my_test_module is executed.


2nd possibility: Invoke my_test_module.py as a script

Now if you run my_test_module.py as a Python script, both print() statements will be exectued:

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'

回答 23

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不会执行。

Every module in python has a attribute called __name__. The value of __name__ attribute is __main__ when the module is run directly, like python my_module.py. Otherwise (like when you say import my_module) the value of __name__ is the name of the module.

Small example to explain in short.

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

We can execute this directly as

python test.py  

Output

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

Now suppose we call above script from other script

#script external_calling.py

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

print(test.__name__)

When you execute this

python external_calling.py

Output

42
I am inside hello_world
test

So, above is self explanatory that when you call test from other script, if loop __name__ in test.py will not execute.


回答 24

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

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

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

If this .py file are imported by other .py files, the code under “the if statement” will not be executed.

If this .py are run by python this_py.py under shell, or double clicked in Windows. the code under “the if statement” will be executed.

It is usually written for testing.


回答 25

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

运行此脚本打印件时,您可以看到我

一个

如果您导入此文件,请说A到文件B并执行文件B,则if __name__ == "__main__"文件A中的文件将变为false,因此将其打印出来 您看不到我

b

If the python interpreter is running a particular module then __name__ global variable will have value "__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()

When you run this script prints you can see me

a

If you import this file say A to file B and execute the file B then if __name__ == "__main__" in file A becomes false, so it prints You can’t see me

b


回答 26

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

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

All the answers have pretty much explained the functionality. But I will provide one example of its usage which might help clearing out the concept further.

Assume that you have two Python files, a.py and b.py. Now, a.py imports b.py. We run the a.py file, where the “import b.py” code is executed first. Before the rest of the a.py code runs, the code in the file b.py must run completely.

In the b.py code there is some code that is exclusive to that file b.py and we don’t want any other file (other than b.py file), that has imported the b.py file, to run it.

So that is what this line of code checks. If it is the main file (i.e., b.py) running the code, which in this case it is not (a.py is the main file running), then only the code gets executed.


回答 27

创建一个文件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

Create a file, a.py:

print(__name__) # It will print out __main__

__name__ is always equal to __main__ whenever that file is run directly showing that this is the main file.

Create another file, b.py, in the same directory:

import a  # Prints a

Run it. It will print a, i.e., the name of the file which is imported.

So, to show two different behavior of the same file, this is a commonly used trick:

# Code to be run when imported into another python file

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

回答 28

如果name ==’ main ‘:

我们__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‘:

We see if __name__ == '__main__': quite often.

It checks if a module is being imported or not.

In other words, the code within the if block will be executed only when the code runs directly. Here directly means not imported.

Let’s see what it does using a simple code that prints the name of the module:

# test.py
def test():
   print('test module name=%s' %(__name__))

if __name__ == '__main__':
   print('call test()')
   test()

If we run the code directly via python test.py, the module name is __main__:

call test()
test module name=__main__

回答 29

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

Simply, it is the entry point to run the file, like the main function in the C programming language.


if __name__ == ‘__main__’ 的作用和原理

1.一句话总结 if __name__ == ‘__main__’ 作用和原理

if __name__ == ‘__main__’ 是为了保护用户不在无意中(比如import)调用到脚本的主函数部分代码。

比如你在另一个脚本中导入了无 if __name__ == ‘__main__’ 保护的脚本(比如导入 test.py),那么该脚本的主函数会在导入时被触发运行,这有时会造成严重的后果。

如果你在无保护脚本中设置了一个自定义类,并将其保存在一个pickle文件中,在另一个脚本中解开它时就会触发无保护脚本的导入,其问题与上面所述的一样。

如果你看不懂这段描述,请看下面的详解:

2.详解

为了更好地理解这个问题的原因,我们需要退一步理解 Python 是如何初始化脚本的,以及这与它的模块导入机制是如何互动的。

每当 Python 解释器读取一个源文件时,它会做两件事。

  • 它设置了一些特殊变量,例如__name__,然后
  • 它执行文件中找到的所有代码。

让我们看看这是如何工作的,以及它与你关于我们在 Python 脚本中经常看到的 __name__ 检查有什么关系。

2.1 代码样例

假设代码在一个叫做foo.py的文件中。

# Suppose this is foo.py.

print("before import")
import math

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

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

print("before __name__ guard")
if __name__ == '__main__':
    functionA()
    functionB()
print("after __name__ guard")

2.2 运行代码

当Python解释器读取源文件时,它首先会定义一些特殊的变量。比如__name__ 虽然它长得很奇怪,前面和后面都有一个下划线_,但是记得变量命名的规则嘛?下划线_是可以出现在变量首字母的。所以,__name__仍然是一个变量,只不过,是解释器自己定义的。

2.3 作为主程序运行

当我们在命令行中使用python foo.py,或者直接在ide(比如pycharm)图形界面里点运行 foo.py,那么这时候,foo.py就是作为主程序运行的。

此时: Python解释器会直接给_name_变量赋值为”_main_

2.2 作为导入的模块运行

如果有另一个程序,叫 main.py,它里面的代码是这样的。

import foo

那么如果我们在命令行中使用 python main.py, 则 main.py 作为主程序运行,而foo.py就是导入的模块。

此时: Python解释器会令 __name__ = "foo"

2.3 执行foo.py文件中的代码

如果使用主程序运行!python foo.py: 输出如下:

    before import
    before functionA
    before functionB
    before __name__ guard
    Function A
    Function B 10.0
    after __name__ guard

如果使用主程序运行import foo: 输出如下:

before import
before functionA
before functionB
before __name__ guard
after __name__ guard

可以明显看到,当使用主程序运行import foo时,没有执行下面语句的内容,因为此时__name__ = 'foo'

if __name__ == '__main__':
    functionA()
    functionB()

3.为什么这样工作?

有时我们想编写一个.py文件,该文件既可以被其他程序和模块导入,也可以作为主程序运行。 例子如下:

  • 这个文件是一个库,可以被其他文件导入。但是我们希望可以在其中运行一些单元测试或演示。
  • 这个文件仅用作主程序,但具有一些单元测试的功能,一些测试框架(类似unittestdoctest)需要导入这个.py文件来测试。我们不希望,它只是因为被导入为模块,就直接运行整个脚本。
  • 这个模块主要用作主程序,但它也为高级用户提供了程序员友好的API

所以,其实就是有的时候希望他在被导入的时候运行一些代码,有的时候希望他作为主程序的时候运行另一些代码。所以需要进行判断。

我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。

有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。

原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!

给作者打赏,选择打赏金额
¥1¥5¥10¥20¥50¥100¥200 自定义

​Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典