1. 程式人生 > >python模組匯入問題和if __name__ == '__main__'語句的使用

python模組匯入問題和if __name__ == '__main__'語句的使用

1. 匯入模組時,如果匯入的新模組不在當前模組所在同一路徑下,那麼直接import會出錯。解決辦法有:

(1)如果當前模組和要匯入的模組屬於不同的包,但是包的上級路徑是一樣的,那麼可以直接import 包名.模組名,如import myPackeg.myModule

(2)可以先將要匯入的模組加入sys.path中,再import. 如下示例:匯入F:\DeepLearning目錄下的test1模組

>>> import test1
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import test1
ModuleNotFoundError: No module named 'test1'
>>> import sys
>>> sys.path
['', 'D:\\Program Files\\Python\\Lib\\idlelib', 'D:\\Program Files\\Python\\python36.zip', 'D:\\Program Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python', 'D:\\Program Files\\Python\\lib\\site-packages']
>>> sys.path.append('F:\\DeepLearning')
>>> sys.path
['', 'D:\\Program Files\\Python\\Lib\\idlelib', 'D:\\Program Files\\Python\\python36.zip', 'D:\\Program Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python', 'D:\\Program Files\\Python\\lib\\site-packages', 'F:\\DeepLearning']
>>> import test1
>>> 

2. if  __name__ == '__main__'語句的使用

先看tc模組和calc模組的程式碼

calc模組程式碼:

import tc
print("32攝氏度 = %.2f華氏度"%tc.c2f(32))
print("99華氏度 = %.2f攝氏度"%tc.f2c(99))
tc模組程式碼:
def c2f(cel):
    fah = cel * 1.8 + 32
    return fah

def f2c(fah):
    cel = (fah - 32) / 1.8
    return cel

def test():
    print("測試,0攝氏度 = %.2f華氏度"%c2f(0))
    print("測試,0華氏度 = %.2f攝氏度"%f2c(0))

test()
執行calc模組後:
>>> runfile('F:/DeepLearning/calc.py', wdir='F:/DeepLearning')
Reloaded modules: tc
測試,0攝氏度 = 32.00華氏度
測試,0華氏度 = -17.78攝氏度
32攝氏度 = 89.60華氏度
99華氏度 = 37.22攝氏度
將測試語句的函式test()也執行了,如果要避免直接執行test()函式,可以將tc模組中最後一句test()語句改為:
if __name__ == '__main__':
    test()
再執行就是
>>>     runfile('F:/DeepLearning/calc.py', wdir='F:/DeepLearning')
Reloaded modules: tc
32攝氏度 = 89.60華氏度
99華氏度 = 37.22攝氏度

檢視__name__屬性:

>>> __name__
'__main__'
>>> tc.__name__
'tc'

這是因為__name__就是標識模組的名字的一個系統變數。這裡分兩種情況:假如當前模組是主模組(也就是呼叫其他模組的模組),那麼此模組名字就是__main__,通過if判斷這樣就可以執行“__main__:”後面的主函式內容;假如此模組是被import的,則此模組名字為檔名字(不加後面的.py),通過if判斷這樣就會跳過“__mian__:”後面的內容。上例中,tc.__name__不是'main',所以tc模組中的“__mian__:”後面的語句就沒有被執行。