color 輸出 else 理解 style blog another 目的 主程

Python中if __name__ == "__main__": 的作用

在很多python腳本中在最後的部分會執行一個判斷語句if __name__ == "__main__:",之後還可能會有一些執行語句。那添加這個判斷的目的何在?

在python編譯器讀取源文件的時候會執行它找到的所有代碼,而在執行之前會根據當前運行的模塊是否為主程序而定義變量__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        # start executing one.py

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

運行python two.py 輸出如下:

[email protected]:~/test$ python3 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

Python中if __name__ == "__main__": 的作用 (整理轉自Arkenstone) --感謝!