python中的 if __name__ == “__main__”: 有什么用?

https://stackoverflow.com/questions/419163/what-does-if-name-main-do#

问题:

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

解答:

当 Python 解释器读取源文件时, 它将执行在其中找到的所有代码。

在执行代码之前, 它将定义一些特殊的变量。例如, 如果 Python 解释器正在将该模块 (源文件) 作为主程序运行, 则会将特殊的 "name" 变量设置为具有值 "main "。如果从另一个模块导入此文件, "name" 将被设置为模块的名称。

在您的脚本的情况下, 让我们假设它的执行作为主要功能, 例如, 你说的东西像

python threading_example

在命令行上。设置特殊变量后, 它将执行导入语句并加载这些模块。然后, 它将评估 def 块, 创建一个函数对象, 并创建一个名为 myfunction 的变量, 指向函数对象。然后, 它将读取 if 语句, 并看到 name 执行相等 "main ", 因此它将运行显示在那里的块。

这样做的一个原因是, 有时您编写的模块 (. py 文件) 可以直接执行。或者, 它也可以导入并在另一个模块中使用。通过执行main检查, 只有当您希望将模块作为程序运行时才执行该代码. 而当有人只想导入您的模块并调用您的函数时, 不执行main函数。

原文:

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the Python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "main". If this file is being imported from another module, __name__ will be set to the module's name.

In the case of your script, let's assume that it's executing as the main function, e.g. you said something like

python threading_example.py

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that name does equal "main", so it will execute the block shown there.

One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.