1. 程式人生 > >python __name__=='__main__'

python __name__=='__main__'

other rect inf 程序 方便 style run bsp 是否

在很多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 ,輸出:

top-level in
one.py one.py is being imported into another module top-level in one.py func() in one.py two.py is being run directly

python __name__=='__main__'