首頁  >  文章  >  後端開發  >  如何在Python中找到目前模組名稱?

如何在Python中找到目前模組名稱?

WBOY
WBOY轉載
2023-08-27 08:41:06916瀏覽

如何在Python中找到目前模組名稱?

模組可以透過查看預先定義的全域變數 __name__ 來找到自己的模組名稱。如果其值為“__main__”,則程式會作為腳本運行。

範例

def main():
   print('Testing…...')
   ...
if __name__ == '__main__':
   main()

輸出

Testing…...

通常透過匯入使用的模組也提供命令列介面或自測試,並且僅在檢查 __name__ 後才執行此程式碼。

__name__是Python語言中的內建變量,我們可以寫一個程式來查看這個變數的值。這是一個例子。我們還將檢查類型 -

範例

print(__name__)
print(type(__name__))

輸出

__main__
<type 'str'>

範例

Let’s see another example -

我們有一個檔案 Demo.py。

def myFunc():
   print('Value of __name__ = ' + __name__)
if __name__ == '__main__':
   myFunc()

輸出

Value of __name__ = __main__

範例

Now, we will create a new file Demo2.py. In this we have imported Demo and called the function from Demo.py.

import Demo as dm

print('Running the imported script')
dm.myFunc()

print('\n')
print('Running the current script')
print('Value of __name__ = ' + __name__)

輸出

Running the imported script
Value of __name__ = Demo

Running the current script
Value of __name__ = __main__

以上是如何在Python中找到目前模組名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除