標籤:alt 管理 write logging inf 模組 ... dirname turn
匯入新的模組
建立一個 calculate.py 檔案
print(‘ok‘)def add(x,y): return x + ydef sub(x,y): return x - y
再建立一個 bin.py 檔案調用 calculate.py 模組
import sysimport calculate # 匯入 calculate 模組, 模組會在 sys.path 中搜尋print(calculate.add(1,2)) # 調用 calculate 模組中的 add 方法,需要寫成 calculate.add()print(sys.path) # 查看 pyton 搜尋模組運行結果:ok3[‘D:\\python_script\\alex_test\\day20‘, ‘D:\\python_script\\alex_test‘, ‘D:\\python35\\python35.zip‘, ‘D:\\python35\\DLLs‘, ‘D:\\python35\\lib‘, ‘D:\\python35‘, ‘D:\\python35\\lib\\site-packages‘]
通過 from ... import 方法來進行調用 calculate 模組中的方法
from calculate import add,subprint(add(1,2)) # 直接使用 add() 進行調用運行結果:ok3
建立別名
from calculate import add as plus # 這裡程式只能調用 plus,而 add 則會失效# print(add(1,2)) 報 NameError: name ‘add‘ is not defined 錯誤print(plus(1,2))運行結果:ok3
調用其他目錄下的模組
logger.py 檔案內容
def write_log(): print("logging")
兩種方式進行調用
#方法一:from web.logger import write_logwrite_log()運行結果:logging#方法二:from web import loggerlogger.write_log()運行結果:logging
注意,如果模組下面的 __ init__ .py 的檔案內容,import 和 from...import 都會執行 __ init__ .py 中的語句。
匯入模組的時候注意模組的路徑
import os,sysBABE_DIR = os.path.dirname(os.path.dirname(__file__))# 通過 __file__ 擷取當前執行檔案的路徑及名稱# 通過 os.path.dirname() 獲得上一級的路徑sys.path.append(BABE_DIR) # 系統執行環境添加需要的路徑print(sys.path)
Python 模組管理