python自定義模塊使用.pth文件實現(xiàn)重用方式
python自定義模塊使用.pth文件實現(xiàn)重用
關(guān)于自定義模塊重用的最好辦法是打包發(fā)布到pypi然后使用pip進行安裝,但是有些模塊是項目內(nèi)部使用的不方便公開的可以使用.pth實現(xiàn)自動引入
關(guān)于python的.pth文件的功能參考:
具體操作
1. 在python的 Lib/site-packages 目錄新建.pth文件
2. 編輯.pth文件,添加要重用的模塊目錄,多個目錄編輯多行

然后D:\py\base目錄中的模塊就可以直接import導入使用了
以下是我寫的自動添加模塊到.pth的腳本in_lab.py
import os
import shutil
python_path = shutil.which("python")
python_path = os.path.dirname(python_path)
if python_path.startswith("/"):
python_path = python_path[1] + ":" + python_path[2:]
print(python_path)
lib_path = os.path.join(python_path, "lib")
if not os.path.exists(lib_path):
lib_path = os.path.join(os.path.dirname(python_path), "lib")
pth_file = os.path.join(lib_path, "site-packages", ".pth")
print(pth_file)
pwd = os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(pth_file):
with open(pth_file, "w") as f:
f.write(pwd + "\n")
else:
with open(pth_file, "r") as f:
content = f.read()
if pwd not in content:
with open(pth_file, "a") as f:
f.write(pwd + "\n")在需要添加的模塊中生成in_lab.py
然后在當前使用的python環(huán)境運行
python d:/py/base/in_lab.py
這樣就可以自動添加d:/py/base到.pth了
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pytorch中DataLoader()過程中遇到的一些問題
這篇文章主要介紹了pytorch中DataLoader()過程中遇到的一些問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
django中的select_related和prefetch_related性能優(yōu)化分析
這篇文章主要介紹了django中的select_related和prefetch_related性能優(yōu)化分析,本文給大家介紹的非常詳細,需要的朋友可以參考下2024-07-07
python環(huán)境搭建Makefile簡單使用步驟
Makefile是一種自動化構(gòu)建工具,通過定義規(guī)則、依賴關(guān)系和執(zhí)行命令,替代手動重復敲編譯、運行和清理等指令,提升開發(fā)效率,本文給大家介紹python環(huán)境搭建Makefile簡單使用方法,感興趣的朋友跟隨小編一起看看吧2026-02-02

