標籤:ref col div 代碼 art 檔案的 else port bsp
Python中if __name__ == "__main__": 的作用
在很多python指令碼中在最後的部分會執行一個判斷語句if __name__ == "__main__:",之後還可能會有一些執行語句。那添加這個判斷的目的何在?
在python編譯器讀取源檔案的時候會執行它找到的所有代碼,而在執行之前會根據當前啟動並執行模組是否為主程式而定義變數__name__的值為__main__還是模組名。因此,該判斷語句為真的時候,說明當前啟動並執行指令碼為主程式,而非主程式所引用的一個模組。這在當你想要運行一些只有在將模組當做程式運行時而非當做模組引用時才執行的命令,只要將它們放到if __name__ == "__main__:"判斷語句之後就可以了。
具體舉個栗子方便理解:
# file one.pydef 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.pyimport one # start executing one.pyprint("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.pyone.py is being run directly
運行python two.py 輸出如下:
[email protected]:~/test$ python3 two.pytop-level in one.pyone.py is being imported into another moduletop-level in two.pyfunc() in one.pytwo.py is being run directly
Python中if __name__ == "__main__": 的作用 (整理轉自Arkenstone) --感謝!