Python基礎-__main__


Python基礎-_main_

寫在前面

如非特別說明,下文均基於Python3

一、__main__的官方解釋

參考 _main_ -- Top-level script environment

'_main_' is the name of the scope in which top-level code executes. A module’s _name_ is set equal to '_main_' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own _name_, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == "__main__":
    # execute only if run as a script
    main()

For a package, the same effect can be achieved by including a _main_.py module, the contents of which will be executed when the module is run with -m.

__main__是頂層代碼執行環境的名字。當一個模塊從標准輸入,腳本或者解釋器提示行中被讀取時,模塊的__name__屬性被設置成__main__

模塊可以依據檢查__name__屬性是否為__main__的方式自我發現是否在main scope中,這允許了一種在模塊中條件執行代碼的常見用法,當模塊作為腳本或者使用python -m命令運行時執行,而被導入時不執行:

if __name__ == "__main__":
    # 當且僅當模塊作為腳本運行時執行main函數
    main()

對於包而言,可以在包中包含一個名為__main__.py的模塊到達相同的效果,當模塊使用python -m命令運行時,__main__py模塊的內容會被執行。

二、__main__實踐

第一節中說過,當模塊從標准輸入,腳本或者解釋器命令行中被讀取時,其__name__屬性被設置為__main__ ,導入時值為模塊名字。那么就可以根據這兩種不同情況執行不同的代碼。

Make a script both importable and executable

讓腳本即可執行又可被導入,是對__main__這一特性最好的詮釋:


def test():
	print('This is test method in com.richard.other')

def main():
	test()

if __name__ == '__main__':

	print('直接運行時,__name__屬性:', __name__)
	main()
else:
	# 導入時被執行
	print('導入時,__name__屬性:', __name__)

直接運行時,輸出:

直接運行時,__name__屬性: __main__
This is test method in com.richard.other

導入時,輸出:

>>> import com.richard.other.test as ctest
導入時,__name__屬性: com.richard.other.test
>>> 

這樣,可以在if __name__ == '__main__':的判斷下加入對這個模塊的測試代碼,就可以在不影響外部模塊引用該模塊的條件下,調試我們的模塊了。

NOTICE: 示例在python 3+解釋器中成功運行,的模塊名為test.py,其包結構如下:

test.py包層次結構

目錄sublime已加入python解釋器sys.path變量中。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM