---
title: "將我的第一個 Python 套件發布到 PyPI"
url: https://sammy.hk/%e5%b0%87%e6%88%91%e7%9a%84%e7%ac%ac%e4%b8%80%e5%80%8b-python-%e5%a5%97%e4%bb%b6%e7%99%bc%e5%b8%83%e5%88%b0-pypi/
author: Sammy Fung
published: 2025-02-14T17:13:35+08:00
modified: 2025-07-15T21:23:29+08:00
description: "一般公司和家庭用家都會透過 router 連接互聯網，他們電腦和手機平板甚至 Server 和 NAS 都是連接 router 的單位內的私人 WIFI 或 LAN，不輕易得知公司或家中在互聯網上的真正 IP 地址。 我擁有一個易記的域名 router.hk 已經多年。之前我開發了一個 IP 地址查詢工具，幫助 Lin…"
categories: ["開放源碼"]
tags: [python]
source: https://sammy.hk
---
[![](https://sammy.hk/wp-content/uploads/2025/02/routerhk-·-PyPI.png)](https://sammy.hk/wp-content/uploads/2025/02/routerhk-·-PyPI.png)一般公司和家庭用家都會透過 router 連接互聯網，他們電腦和手機平板甚至 Server 和 NAS 都是連接 router 的單位內的私人 WIFI 或 LAN，不輕易得知公司或家中在互聯網上的真正 IP 地址。

 我擁有一個易記的域名 router.hk 已經多年。之前我開發了一個 IP 地址查詢工具，幫助 Linux 和網絡管理員以及一般用家取得互聯網上的 IP 地址。上星期，我開發了一個更新版本的 API，可以通過簡單的 curl 命令得到 IP 地址。

這星期，我嘗試為它開發一個 Python 套件並上傳到 PyPI（Python Package Index）。開發 Python 套件需要更好的文件結構和附加文件。

PyPI: <https://pypi.org/project/routerhk/>
GitHub: <https://github.com/routerhk/routerhk>

文件結構

routerhk/
├── routerhk/
│ ├── **init**.py
│ └── routerhk.py
├── tests/
│ └── test\_routerhk.py
├── setup.py
├── README.md
├── requirements.txt
└── LICENSE

1. 我的套件具有上述結構。
2. 在 routerhk.py 中開發一個 RouterHk Class，並從 routerhk/**init**.py 中調用它，手動測試該Class 及其 Functions。
3. 編寫 test\_routerhk.py，我使用 unittest。 
    1. `python -m unittest tests/test_routerhk.py`
    2. 我可能會稍後改回 pytest。
4. 參考其他 Python 套件來創建 setup.py，以便讓 PyPI 設立套件資料。 
    1. `pip install setuptools wheel`
    2. `python setup.py sdist bdist_wheel`
    3. `pip install .`
    4. 從其他目錄測試安裝的本地 Python 套件。
5. 上傳到 PyPI 
    1. `pip install twine`
    2. `twine upload dist/*`
    3. 輸入 API Token 並將套件上傳到 PyPI。

我的 PyPI 帳戶於 2016 年創建。我在 pypi.org 上創建了一個 API token，並用它上傳套件。

使用 routerhk 的示例代碼：

> from routerhk import RouterHK
> r = RouterHK()
> r.get\_ip()

參考資料：

- unittest 基礎示例: <https://docs.python.org/3/library/unittest.html#basic-example>
- Python Packaging User Guide: <https://packaging.python.org/en/latest/>
- The Packaging Flow: <https://packaging.python.org/en/latest/flow/>

### 相關文章：

1. [寫 Python程式去追風](https://sammy.hk/use-python-to-track-tropical-cyclone/ "寫 Python程式去追風")
2. [Twitter x OAuth x Python = Tweepy](https://sammy.hk/twitter-oauth-python-tweepy/ "Twitter x OAuth x Python = Tweepy")
3. [Pynguin 自動產生 Python 單元測試](https://sammy.hk/pynguin-%e8%87%aa%e5%8b%95%e7%94%a2%e7%94%9f-python-%e5%96%ae%e5%85%83%e6%b8%ac%e8%a9%a6/ "Pynguin 自動產生 Python 單元測試")
4. [2021 Python 軟件基金會董事會改選](https://sammy.hk/2021-python-%e8%bb%9f%e4%bb%b6%e5%9f%ba%e9%87%91%e6%9c%83%e8%91%a3%e4%ba%8b%e6%9c%83%e6%94%b9%e9%81%b8/ "2021 Python 軟件基金會董事會改選")
