做一個自己的 Python Packge
Mon, Apr 10, 2023 1:21 PM
最近因為工作上需要將 Excel 檔案轉成 iOS
、Android
專案可用的語言包,由於以前有其他同事分享的 php
程式碼又加上最近有接觸一點 Python
,剛好藉此機會寫寫 Python
的腳本。
至於為什麼會需要打包成 Packge
?主因是維護方便,原先預計這個腳本就單純 iOS
專案自己使用,但因為需求兩邊平台一致變成也要同時支援 Android
;加上我不想同時維護兩邊的專案,綜述以上種種就來打包成 Packge
吧。
讓我們開始吧
Pythone 版本因應你的程式碼,這裡沒有特別限制
1. 能跑的 code
有一份可以跑的程式碼,不論複雜與否都可以。
2. 安裝依賴套件
modern-package-template 大約已有 13 年未更新,模板生成之後有部分錯誤需要手動修復。
-
$ pip3 install modern-package-template
3. 建立 Package 專案
-
$ paster create -t modern_package {自訂名稱}
-
- 依照提示填入相應訊息
-
- 修復錯誤
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
4. 調整 Package 的資訊
-
- 打開
setup.py
,可以在此調整版本或者介紹
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
5. 在 venv 安裝 Package
因為是透過模板產生的 Package 專案,裡面有 venv 虛擬環境方便測試、安裝
-
$ python setup.py install
-
- 執行完成後你會發現多了這兩個目錄
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
-
- 使用
$ pip show {自訂名稱}
來檢查安裝的結果
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
6. 執行
建立一個空白 Python,import 進來並執行
-
- 當你看到
Hello World
,你就成功了一半
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
-
- 剩下的一半就是把你要打包的程式碼逐一搬進專案中
src/{自訂名稱}
的目錄下 (例)
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
7. 再次執行
當修改過 src
目錄下的程式碼
請記得再跑過 $ python setup.py install
,確保測試環境中的 Package
在修改後的版本
還記得標題嗎?做一個自己的 Python Package
顧名思義,這是一個 Private
的 Python Package,所以我並沒有要讓他推上 PyPI
;而是使用 Git
Repository。
1. Git
若你是位成熟的工程師,想必這個不必我多描述。
2. 使用與安裝
-
$ pip install git+{git repository ssh}
-
- 使用方式就如同在虛擬環境一樣。
3. You done
這樣你就完成了自己的 Python Package,很容易吧 🎉