Python 的頂層指令碼環境(__main__)
模組物件具有各種屬性。屬性名稱以雙下劃線 __ 為字首和字尾。模組最重要的屬性是 __name__。當 Python 作為頂層可執行程式碼執行時,即當從標準輸入、指令碼或互動式提示符讀取時,__name__ 屬性設定為 '__main__'。
>>> __name__ '__main__'
在指令碼內部,我們也發現 __name__ 屬性的值被設定為 '__main__'。執行以下指令碼。
'module docstring'
print ('name of module:',__name__)輸出
name of module: __main__
但是,對於匯入的模組,此屬性設定為 Python 指令碼的名稱。對於 hello.py 模組
>>> import hello >>> hello.__name__ hello
如前所述,頂層模組的 __name__ 值設定為 __main__。但是,對於匯入的模組,它設定為檔名稱。執行以下指令碼 (moduletest.py)
import hello
print ('name of top level module:', __name__)
print ('name of imported module:', hello.__name__)輸出
name of top level module: __main__ name of imported module: hello
包含函式的 Python 指令碼也可能具有一定的可執行程式碼。因此,如果我們匯入它,它的程式碼將自動執行。我們有這個指令碼 messages.py,其中包含兩個函式。在可執行部分,使用者輸入作為引數提供給 thanks() 函式。
def welcome(name):
print ("Hi {}. Welcome to TutorialsPoint".format(name))
return
def thanks(name):
print ("Thank you {}. See you again".format(name))
name = input('enter name:')
thanks(name)顯然,當我們執行 messages.py 時,輸出顯示如下感謝訊息。
enter name:Ajit Thank you Ajit. See you again
我們有一個 moduletest.py 指令碼如下。
import messages
print ('name of top level module:', __name__)
print ('name of imported module:', messages.__name__)現在,如果我們執行 moduletest.py 指令碼,我們會發現輸入語句和對 welcome() 的呼叫將被執行。
c:\python37>python moduletest.py
輸出
enter name:Kishan Thank you Kishan. See you again enter name:milind Hi milind. Welcome to TutorialsPoint
這是兩個指令碼的輸出。但想要從 messages 模組匯入函式,但不希望其中包含的可執行程式碼執行。
這就是頂層指令碼的 __name__ 屬性值為 __main__ 的有用之處。修改 messages.py 指令碼,使其僅當 __name__ 等於 __main__ 時才執行輸入和函式呼叫語句。
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to TutorialsPoint".format(name))
return
def thanks(name):
print ("Thank you {}. See you again".format(name))
if __name__=='__main__':
name = input('enter name')
thanks(name)無論何時想要一個既可以執行又可以匯入的模組,都可以使用上述技術。moduletest.py 不需要任何更改。messages 模組中的可執行部分現在不會執行。
enter name: milind Hi milind. Welcome to TutorialsPoint
請注意,這不會阻止您獨立執行 messages.py 指令碼。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP