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.