寫在前面
如非特別說明喉酌,下文均基于
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__
是頂層代碼執(zhí)行環(huán)境的名字揍魂。當(dāng)一個(gè)模塊從標(biāo)準(zhǔn)輸入卓鹿,腳本或者解釋器提示行中被讀取時(shí)粥烁,模塊的__name__
屬性被設(shè)置成__main__
。
模塊可以依據(jù)檢查__name__
屬性是否為__main__
的方式自我發(fā)現(xiàn)是否在main scope
中蝇棉,這允許了一種在模塊中條件執(zhí)行代碼的常見用法讨阻,當(dāng)模塊作為腳本或者使用python -m
命令運(yùn)行時(shí)執(zhí)行,而被導(dǎo)入時(shí)不執(zhí)行:
if __name__ == "__main__":
# 當(dāng)且僅當(dāng)模塊作為腳本運(yùn)行時(shí)執(zhí)行main函數(shù)
main()
對(duì)于包而言篡殷,可以在包中包含一個(gè)名為__main__.py
的模塊到達(dá)相同的效果钝吮,當(dāng)模塊使用python -m
命令運(yùn)行時(shí),__main__py
模塊的內(nèi)容會(huì)被執(zhí)行板辽。
二奇瘦、_main_實(shí)踐
第一節(jié)中說過,當(dāng)模塊從標(biāo)準(zhǔn)輸入劲弦,腳本或者解釋器命令行中被讀取時(shí)耳标,其__name__
屬性被設(shè)置為__main__
,導(dǎo)入時(shí)值為模塊名字邑跪。那么就可以根據(jù)這兩種不同情況執(zhí)行不同的代碼次坡。
Make a script both importable and executable
讓腳本即可執(zhí)行又可被導(dǎo)入呼猪,是對(duì)__main__
這一特性最好的詮釋:
def test():
print('This is test method in com.richard.other')
def main():
test()
if __name__ == '__main__':
print('直接運(yùn)行時(shí),__name__屬性:', __name__)
main()
else:
# 導(dǎo)入時(shí)被執(zhí)行
print('導(dǎo)入時(shí)砸琅,__name__屬性:', __name__)
直接運(yùn)行時(shí)宋距,輸出:
直接運(yùn)行時(shí),__name__屬性: __main__
This is test method in com.richard.other
導(dǎo)入時(shí)症脂,輸出:
>>> import com.richard.other.test as ctest
導(dǎo)入時(shí)谚赎,__name__屬性: com.richard.other.test
>>>
這樣,可以在if __name__ == '__main__':
的判斷下加入對(duì)這個(gè)模塊的測(cè)試代碼诱篷,就可以在不影響外部模塊引用該模塊的條件下壶唤,調(diào)試我們的模塊了。
NOTICE: 示例在python 3+
解釋器中成功運(yùn)行兴蒸,的模塊名為test.py
视粮,其包結(jié)構(gòu)如下:
目錄sublime
已加入python
解釋器sys.path
變量中。