2025年8月20日 星期三

Python 學習筆記 : 將 K 線圖模組 kbar.py 打包上傳 PyPI (二)

由於篇幅太長了, 所以我將整篇記錄拆成三篇, 此為中篇. 本系列前一篇文章參考 :


Python 量化投資筆記索引參考 :


本篇繼續來進行套件打包作業. 


4. 編輯單元測試 unittest 程式檔 :  

抄錄前篇所配置的檔案目錄結構 :

D:\pypi>tree kbar /f     
列出磁碟區 新增磁碟區 的資料夾 PATH
磁碟區序號為 1258-16B8
D:\PYPI\KBAR
│  LICENSE
│  pyproject.toml
│  README.md
├─src
│  └─kbar
│       │   kbar.py
│       └─ __init__.py
└─tests
    │   test_kbar.py
    └─__init__.py

在 tests 資料夾底下的 test_kbar.py 是用來測試套件功能的單元測試程式, 可以在檔案中利用 unittest 套件撰寫測試邏輯, 但也可以是一個空檔案或將整個 test 子目錄移除, 這並不會影響套件的打包與上傳, PyPI 可以接受發佈的套件中沒有 test 資料夾或測試程式為空檔案. 

雖然我還不會用 unittest, 但為了套件的完整性, 還是請 ChatGPT 幫忙生成了一個 test_kbar.py 測試檔, 提示詞如下 :

"請為上面的 kbar.py 寫一個在套件子目錄 tests 下的 test_kbar.py  檔案"

經過了幾次除錯之後得到如下的單元測試程式 :

# test_kbar.py
import unittest
import pandas as pd
import numpy as np
from kbar import KBar, detect_font

class TestKBar(unittest.TestCase):
    def setUp(self):
        # 建立測試用的 DataFrame
        data = {
            'Open': [100, 102, 101, 105],
            'High': [103, 106, 104, 108],
            'Low': [99, 100, 98, 102],
            'Close': [102, 104, 103, 107],
            'Volume': [1000, 1500, 1200, 1300],
        }
        self.df = pd.DataFrame(data, index=pd.date_range(start="2023-01-01", periods=4))
        self.kbar = KBar(self.df)

    def test_initialization(self):
        # 測試初始化是否正確
        self.assertEqual(len(self.kbar.addplots), 0)
        pd.testing.assert_frame_equal(self.kbar.df, self.df)

    def test_font_detection(self):
        # 測試是否能偵測到字型(不保證一定有中文,但至少不應該 None)
        font = detect_font()
        self.assertIsNotNone(font)

    def test_addplot(self):
        # 測試 addplot 方法
        data = self.df['Close']
        self.kbar.addplot(data, color='red', linestyle='--', width=2)
        self.assertEqual(len(self.kbar.addplots), 1)

    def test_addplot_content(self):
        # 驗證 addplot 內容正確性
        data = self.df['Close']
        self.kbar.addplot(data, color='blue')
        plot_obj = self.kbar.addplots[0]
        # 驗證資料長度一致
        self.assertEqual(len(plot_obj.get_data()[1]), len(self.df))

    def test_plot_without_returnfig(self):
        # 測試 plot 方法不傳回圖表
        try:
            self.kbar.plot(volume=True, title='Test Plot', ylabel='Price')
        except Exception as e:
            self.fail(f"plot() raised an exception: {e}")

    def test_plot_with_returnfig(self):
        # 測試 plot 方法傳回圖表
        fig, axes = self.kbar.plot(returnfig=True, volume=True, title='Test Plot')
        self.assertTrue(hasattr(fig, "axes"))
        self.assertGreaterEqual(len(fig.axes), 2)  # 檢查有主圖與成交量副圖

    def test_plot_with_returnfig_axes_labels(self):
        # 測試標題是否被正確設定
        fig, axes = self.kbar.plot(returnfig=True, volume=True, title='My Test Title')
        self.assertIn('My Test Title', fig._suptitle.get_text())

    def test_invalid_addplot_data(self):
        # 測試傳入錯誤型別資料
        with self.assertRaises(TypeError):
            self.kbar.addplot("invalid_data")

    def test_plot_with_custom_params(self):
        # 測試自訂參數的情況
        try:
            self.kbar.plot(
                volume=True,
                figscale=1.2,
                figratio=(10, 6),
                tight_layout=True,
                xrotation=30,
            )
        except Exception as e:
            self.fail(f"plot() raised an exception with custom params: {e}")


if __name__ == "__main__":
    unittest.main()

開啟命令提示字元視窗, 切換至專案目錄 (此處是 D:\pypi\kbar) 下 :

D:\cd pypi\kbar  

然後執行下列編輯模式安裝指令 (editable install) : 

pip install -e .  

這會把 src/kbar 安裝到 Python 的 site-packages, 但 Python 不是把 kbar 套件複製到 site-packages 去安裝, 而是建立一個指向 kbar 專案原始碼的連結, 這樣在專案目錄改檔案時, Python 就會直接看到改動, 對開發與做單元測試都非常方便, 這樣 unittest 測試程式中就能直接使用 from kbar import KBar 匯入指令了 :

D:\PyPi\kbar>pip install -e .   
Obtaining file:///D:/PyPi/kbar
  Installing build dependencies ... done
  Checking if build backend supports build_editable ... done
  Getting requirements to build editable ... done
  Preparing editable metadata (pyproject.toml) ... done
Requirement already satisfied: mplfinance>=0.12.10b0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from kbar==0.1.0) (0.12.10b0)
Requirement already satisfied: matplotlib in c:\users\tony1\appdata\roaming\python\python310\site-packages (from mplfinance>=0.12.10b0->kbar==0.1.0) (3.7.2)
Requirement already satisfied: pandas in c:\users\tony1\appdata\roaming\python\python310\site-packages (from mplfinance>=0.12.10b0->kbar==0.1.0) (2.0.3)
Requirement already satisfied: contourpy>=1.0.1 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.3.2)
Requirement already satisfied: cycler>=0.10 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (4.42.1)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.4.5)
Requirement already satisfied: numpy>=1.20 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.24.3)
Requirement already satisfied: packaging>=20.0 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (24.2)
Requirement already satisfied: pillow>=6.2.0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (9.5.0)
Requirement already satisfied: pyparsing<3.1,>=2.3.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (2.8.2)
Requirement already satisfied: six>=1.5 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from python-dateutil>=2.7->matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.16.0)
Requirement already satisfied: pytz>=2020.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->mplfinance>=0.12.10b0->kbar==0.1.0) (2023.3)
Requirement already satisfied: tzdata>=2022.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->mplfinance>=0.12.10b0->kbar==0.1.0) (2023.3)
Building wheels for collected packages: kbar
  Building editable for kbar (pyproject.toml) ... done
  Created wheel for kbar: filename=kbar-0.1.0-0.editable-py3-none-any.whl size=4690 sha256=527ec2e5c2c4049a82bfe4d916e3772146cbe77bbd588b98ad8f1600c9cf803d
  Stored in directory: C:\Users\tony1\AppData\Local\Temp\pip-ephem-wheel-cache-9ztfpvmy\wheels\c7\71\74\270f8495f568015ac5455877b0405b5fcc7d494f35cddcfb43
Successfully built kbar
Installing collected packages: kbar
Successfully installed kbar-0.1.0

有了編輯模式安裝, 即可順利執行 unittest 程式 (就不會出現找不到模組之錯誤) : 

python -m unittest discover -s tests   

D:\PyPi\kbar>python -m unittest discover -s tests  
設定字型為: Microsoft JhengHei
.設定字型為: Microsoft JhengHei
.設定字型為: Microsoft JhengHei
.設定字型為: Microsoft JhengHei
.設定字型為: Microsoft JhengHei
.設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']
.設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']
.設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']
.設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']
.
----------------------------------------------------------------------
Ran 9 tests in 99.423s

OK

結果會跳出 4 張測試結果的圖, 這表示測試 OK, 將其一一關掉即可 :







做完單元測試後,  在正式發佈前要先解除 -e 模式 : 

D:\PyPi\kbar>pip uninstall kbar -y   
Found existing installation: kbar 0.1.0
Uninstalling kbar-0.1.0:
  Successfully uninstalled kbar-0.1.0

並重新安裝套件 : 

D:\PyPi\kbar>pip install .   
Processing d:\pypi\kbar
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: mplfinance>=0.12.10b0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from kbar==0.1.0) (0.12.10b0)
Requirement already satisfied: matplotlib in c:\users\tony1\appdata\roaming\python\python310\site-packages (from mplfinance>=0.12.10b0->kbar==0.1.0) (3.7.2)
Requirement already satisfied: pandas in c:\users\tony1\appdata\roaming\python\python310\site-packages (from mplfinance>=0.12.10b0->kbar==0.1.0) (2.0.3)
Requirement already satisfied: contourpy>=1.0.1 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.3.2)
Requirement already satisfied: cycler>=0.10 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (4.42.1)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.4.5)
Requirement already satisfied: numpy>=1.20 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.24.3)
Requirement already satisfied: packaging>=20.0 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (24.2)
Requirement already satisfied: pillow>=6.2.0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (9.5.0)
Requirement already satisfied: pyparsing<3.1,>=2.3.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (2.8.2)
Requirement already satisfied: six>=1.5 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from python-dateutil>=2.7->matplotlib->mplfinance>=0.12.10b0->kbar==0.1.0) (1.16.0)
Requirement already satisfied: pytz>=2020.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->mplfinance>=0.12.10b0->kbar==0.1.0) (2023.3)
Requirement already satisfied: tzdata>=2022.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->mplfinance>=0.12.10b0->kbar==0.1.0) (2023.3)
Building wheels for collected packages: kbar
  Building wheel for kbar (pyproject.toml) ... done
  Created wheel for kbar: filename=kbar-0.1.0-py3-none-any.whl size=6626 sha256=fa127e1574e4b8903582507001498cb9a9de3a06cf0c979c5d779a48f246e5e9
  Stored in directory: C:\Users\tony1\AppData\Local\Temp\pip-ephem-wheel-cache-3mnpnz6j\wheels\c7\71\74\270f8495f568015ac5455877b0405b5fcc7d494f35cddcfb43
Successfully built kbar
Installing collected packages: kbar
Successfully installed kbar-0.1.0

以上就完成單元測試了. 


5. 編輯授權檔 LICENCE :  

授權文件不用自己寫, 可以從線上服務取得 (問 ChatGPT 也可以), 例如 https://choosealicense.com/ 網站就可以產生各種授權聲明檔, 我選擇 MIT 授權, 所以點選中間的 "I want it simple and permissive" 圖片按鈕 :




按右上角的 "Copy license text to clipboard" 鈕 :




開啟上面建立的 LICENSE 檔案, 從剪貼簿貼上授權內容, 然後修改 Copyright 後面的年份與姓名後存檔 (注意不要副檔名), 再關閉檔案即可 : 

MIT License

Copyright (c) [2025] [Tony Y.H. Huang]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


6. 編輯讀我檔 README.md :  

這部分同樣請 ChatGPT 代勞, 貼上 kbar.py (有說明文字的) 請它幫我產生一份 README.md 檔, 提示詞如下 :

"請為下列之 kbar.py 模組產生一份可讓我下載的 README.md 檔"

產生的讀我檔內容如下 : 

# 📈 kbar

`kbar` 提供一個簡單的 `KBar` 類別,專門用來繪製金融 K 線圖(candlestick chart)。  
它是 [`mplfinance`](https://github.com/matplotlib/mplfinance) 的輕量級封裝,並額外支援:  

- 🔹 內建成交量副圖(volume)  
- 🔹 自訂技術指標副圖(例如 RSI、MACD)  
- 🔹 自訂疊圖(例如 SMA、均線)  
- 🔹 自動設定中文字型(避免亂碼)  

---

## 🚀 安裝
```bash
pip install kbar
```

---

## 🛠 匯入
```python
from kbar import KBar
# 或
import kbar
```

---

## 📊 使用教學

### 1️⃣ 準備股票價量資料(以 yfinance 為例)
```python
import yfinance as yf
df = yf.download('0050.TW', start='2024-07-01', end='2024-08-21', auto_adjust=False)

# 轉換為單層欄位名稱(避免多層索引)
df.columns = df.columns.map(lambda x: x[0])
```

---

### 2️⃣ 繪製簡單的 K 線圖
```python
kb = KBar(df)
# 或 kb = kbar.KBar(df) 若使用 import kbar
kb.plot()
```

---

### 3️⃣ 繪製含成交量的 K 線圖
```python
kb = KBar(df)
kb.plot(volume=True)  # 成交量副圖會顯示在 panel=1
```

---

### 4️⃣ 添加自訂副圖(例:RSI 指標)
```python
from talib.abstract import RSI

# Ta-Lib 需要欄位小寫
df.columns = [c.lower() for c in df.columns]

rsi = RSI(df)

kb = KBar(df)
kb.addplot(rsi, panel=2, ylabel='RSI')  # RSI 畫在 panel=2
kb.plot(volume=True)
```

---

### 5️⃣ 繪製內建均線(mav)
```python
kb = KBar(df)
kb.plot(mav=5)        # 繪製 5 日均線
# kb.plot(mav=[3,5,7]) # 繪製多條均線
```

---

### 6️⃣ 添加自訂疊圖(例:SMA 均線)
```python
from talib.abstract import SMA

df.columns = [c.lower() for c in df.columns]

sma3 = SMA(df['close'], timeperiod=3)
sma5 = SMA(df['close'], timeperiod=5)
sma7 = SMA(df['close'], timeperiod=7)

kb = KBar(df)
kb.addplot(sma3, panel=0, color='blue', width=1)
kb.addplot(sma5, panel=0, color='orange', width=1)
kb.addplot(sma7, panel=0, color='green', width=1)

kb.plot(volume=True)
```

---

## 📚 API 文件

### `class KBar`

封裝 `mplfinance`,提供簡化的 K 線圖繪製與副圖管理。

#### 🔹 建構子
```python
KBar(df)
```

- **df** (`pandas.DataFrame`):必須包含以下欄位:  
  - `Open`: 開盤價  
  - `High`: 最高價  
  - `Low`: 最低價  
  - `Close`: 收盤價  
  - `Volume`(可選):成交量  

---

#### 🔹 方法:`addplot(data, **kwargs)`
添加自訂副圖或疊圖。  

- **data** (`Series` 或 `ndarray`):要繪製的資料  
- **kwargs**:傳遞給 `mplfinance.make_addplot()` 的參數,例如:  
  - `color`:線條顏色  
  - `width`:線條寬度  
  - `panel`:放置的圖表區(0=主圖,1~9=副圖)  
  - `ylabel`:副圖標籤  

---

#### 🔹 方法:`plot(**kwargs)`
繪製 K 線圖,可同時顯示副圖與疊圖。  

- **kwargs**:傳遞給 `mplfinance.plot()` 的參數,例如:  
  - `volume`:是否顯示成交量副圖  
  - `mav`:均線(整數或整數清單)  
  - `returnfig`:若 `True`,回傳 `(fig, axes)`  

---

## 📘 範例
```python
import yfinance as yf
from kbar import KBar

df = yf.download("0050.TW", start="2024-08-20", end="2025-01-20")
df.columns = df.columns.map(lambda x: x[0])

kb = KBar(df)
kb.addplot(df['Close'].rolling(5).mean(), color='blue', width=1)
kb.plot(volume=True, mav=5)
```

---

## 📦 依賴套件
- `mplfinance`
- `matplotlib`
- `pandas`
- `numpy < 2`
- `pyarrow`(pandas 內部需要)

---

## 📝 授權
MIT License

可以將此 README.md 檔貼到 stackedit.io 線上 Markdown 編輯器左側, 右邊就會顯示內容 (當然也可以用它來手工撰寫讀我檔) : 


將 README.md 存檔備用. 


7. 建立 GitHub 儲存庫 (repository) :  

發布在 PyPI 的套件或模組, 在其首頁都會有一個 HomePage 連結指向此模組或套件的官網, 開發者通常使用 GitHub 作為專案的官網, 將專案原始碼與使用說明文件寄存於儲存庫 (repository), 首先須註冊一個 GitHub 帳號, 參考 :


登入 GitHub 後按右上角 + 鈕再點選 "New repository" :




輸入 repository 名稱為 kbar, 在 description 欄填寫簡要描述, 勾選 "Add README" 後按右下角的 "Create repository" 鈕新增儲存庫 :




完成後會顯示此 kbar 儲存庫的 README.md 檔, 預設就是 description 內容, 按右方的筆按鈕編輯讀我檔 :




複製上一步驟所建立的 README.md 檔內容, 貼到內容編輯框後按右上角的 "Commit changes" 鈕更新讀我檔內容 :





這樣就完成 README.md 更新了 :




此 kbar 儲存庫網址如下 :


此網址在後續的 pyproject.toml 安裝檔中會用到. 


8. 編輯套件建置設定檔 pyproject.toml :  

此設定檔主要作用是告訴 pip 和其他工具下列資訊 :
  • 此專案要使用哪一種建置系統 (build backend, 例如 setuptools 或 poetry等), 如果沒有 pyproject.toml 這個檔案, pip 可能會用舊的方式 (setup.py) 去建置, 而這方式在一些環境中已經被棄用.
  • 在建置前需要安裝什麼套件 (build dependencies) :
    例如使用 setuptools 打包的話就必須在這個檔案裡告訴 pip 要先安裝 setuptools 與 wheel.
簡言之, pyproject.toml 是現代 Python 專案的統一入口文件, 沒有它也能用舊方法將專案上傳到 PyPI, 但有了它可以確保 pip install 指令一定能正常工作, 且建置行為在不同環境中一致, 也能確保未來的相容性, 這也是 2023 後 PyPI 官方推薦的標準打包方式. 

這個 pyproject.toml 內容同樣可請 ChatGPT 代勞, 產出後修改如下 :

[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "kbar"
version = "0.1.2"
description = "A lightweight K-line (candlestick) plotting tool with matplotlib and mplfinance."
readme = "README.md"
requires-python = ">=3.9"
license = { file = "LICENSE" }
authors = [
  { name = "Tony Y.H. Huang" }
]
keywords = ["finance", "candlestick", "mplfinance", "k-line", "stock"]
classifiers = [
  "Development Status :: 3 - Alpha",
  "Intended Audience :: Developers",
  "Intended Audience :: Financial and Insurance Industry",
  "Programming Language :: Python :: 3",
  "License :: OSI Approved :: MIT License",
  "Operating System :: OS Independent"
]

dependencies = [
  "numpy>=1.23,<2",
  "pandas>=2.0,<3.0",
  "matplotlib>=3.7,<4.0",
  "mplfinance>=0.12.10b0",
  "pyarrow>=14.0.2"
]

[project.optional-dependencies]
dev = [
  "pytest>=8.0",
  "coverage>=7.0"
]

[tool.pytest.ini_options]
addopts = "-v --maxfail=3 --disable-warnings"
testpaths = ["tests"]

[tool.coverage.run]
branch = true
source = ["kbar"]

[tool.coverage.report]
show_missing = true
skip_covered = true

[tool.setuptools.packages.find]
where = ["src"]  

[project.urls]
"Homepage" = "https://github.com/tony1966/kbar/"
"Bug Tracker" = "https://github.com/tony1966/kbar/issues"

其中 dependencies 的設定需注意, 由於 matplotlib>=3.7 需要 numpy 至少 1.23 版以上, 不能只寫 <2, 否則可能安裝到低於 1.23 版而安裝失敗. 其次, 因為我有準備 LICENSE 檔, 所以 license 參數使用 file = "LICENSE", 否則就用 text="MIT". authors 參數也可以有 email 屬性, 但容易被拿來寄垃圾信, 所以給 name 即可. 兩個 tool.coverage 參數是用來跑測試覆蓋率用的, 用不到可刪除, 但留著也無妨, 如果會在 CI (例如 GitHub Actions) 或本地定期跑測試覆蓋率, 則保留這段會比較方便 (不用再另外寫 .coveragerc). 另外, 因為之前曾經把只適用於 Windows 的 v0.1.0 發佈到 TestPyPI, 我又不想刪除掉它, 所以本版編號使用 v0.1.1 版. 

另外,  setuptools 版本需至少 61.0, 因為自 61.0 版開始, setuptools 原生支援 PEP 621, 它使用 [project] 區塊來定義專案屬性, 可以完全取代 setup.py 之功能. 這個新式的 REP 621 風格之設定檔使套件在任何環境下執行 pip install 安裝時都會先自動安裝打包需要的工具 (setuptools 與 wheel), 不用再擔心不同 Python 版本的 pip 對 setup.py 直接呼叫的相容性問題. 

以上就完成所有打包前準備工作了, 接下來可以用 Git 把整個專案推送到 GitHub. 


9. 將專案上傳到 GitHub :  

上傳專案到 GitHub 可以在本機安裝版本控制軟體 Git, 然後開啟 Bash 命令列視窗用 git 指令上傳. 但專案中有些檔案例如執行檔快取, 環境變數檔等都不應該上傳, Git 有一個利用 .gitignore 忽略檔的機制, 名列其中的檔案目錄在使用 Git 上傳時會被忽略不上傳. 

開啟記事本輸入如下內容 (這些都是 Python 專案中常見的忽略對象) :

# Python cache
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Virtual environment
venv/
ENV/
env/
.venv/

# PyInstaller
*.manifest
*.spec

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Jupyter Notebook
.ipynb_checkpoints

# IDE / Editor settings
.vscode/
.idea/
*.sublime-project
*.sublime-workspace

# OS files
.DS_Store
Thumbs.db

# Logs
*.log

# Arrow / parquet / tmp
*.parquet
*.arrow
*.tmp

# Local configs
*.env

將以上內容以 .gitignore 為檔名儲存在專案目錄 kbar 底下, 這樣使用 Git 指令上傳專案至 GitHub 時便會自動跳過檔案中所羅列的檔案. 




Git 用法參考 : 


因為我也不是常常要維護多套軟體的版本, 所以就不安裝 Git 了 (很大, 超過 1GB), 直接在 GitHub 網頁上上傳檔案目錄即可. 

登入 GitHub 後, 按搜尋框右邊的 + 按鈕, 選擇 "Upload files" :




開啟檔案總管, 切換至 kbar 專案目錄下, 選取底下的所有檔案與目錄, 然後拖曳到 GitHub 的上傳區, 等全部上傳完成後, 按下方的 "Commit changes" 才算是真正將檔案目錄存入儲存庫 kbar 裡 :




結果如下 : 




這樣便將整個專案寄存在 GitHub 儲存庫裡了. 


沒有留言 :