Python 模組管理

來源:互聯網
上載者:User

標籤: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 模組管理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.