🎇

[備忘録]Pythonパッケージの配布方法

に公開

開発したPythonのパッケージを配布する機会は、そう多くないので備忘録としてまとめる。
最近はLLMに聞けばすぐに分かるが、自分が過去にやった手順は記録しておきたいのでzennに残しておく。

ディレクトリ構成

my_project/
├── my_package/          # ソースコードが入るディレクトリ
│   ├── __init__.py      
│   └── __main__.py
├── tests/               
│   ├── __init__.py
│   └── test_module1.py
├── pyproject.toml      
├── setup.py             
└── README.md            

pyproject.tomlを作成する

[build-system]
requires = ["setuptools>=61.0.0"]
build-backend = "setuptools.build_meta"

[project]
name = "txtra"
version = "0.1.2"
authors = [
  { name="wild0ni0n" },
]
description = "txtra(txt record analyzer) is a tool that profiles the cloud services used by an organization using the txt records returned by name resolution for the domain in question."
readme = "README.md"
requires-python = ">=3.12"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License"
]

dependencies = [
    "colorama==0.4.6",
    "dnspython==2.7.0",
    "PyYAML==6.0.1",
    "tldextract==5.3.0"
]

[project.scripts]
txtra = "txtra.__main__:main"

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

dependencies に記載する依存関係は、 pipreqs で抽出する。

$ pip install pipreqs
$ pipreqs ./ --encoding=utf-8 --force

requirements.txt が生成されるので、中身を dependencies に記載する

setup.pyを作成する

setup.pyは、もっと最小限の書き方もある気がする・・・。

from setuptools import setup
import os

def readme():
    with open('README.md', 'r', encoding='utf-8') as f:
        return f.read()

def strip_comments(l):
    return l.split('#', 1)[0].strip()

def reqs(*f):
    with open(os.path.join(os.getcwd(), *f), encoding='utf-8') as f:
        return [strip_comments(L) for L in f if strip_comments(L)]

setup(
    long_description=readme(),
    install_requires=reqs('requirements.txt'),
    include_package_data=True,
)

パッケージのビルド

$ pip install build
$ python -m build

dist ディレクトリにファイルが出来上がる。

このタイミングで以下のようにpip installコマンドを実行するとローカルで動作を確認することができる

$ pip install ./dist/your_package_name-0.1.0-py3-none-any.whl

PyPIのアカウント登録(未登録の場合)

まだの場合は、アカウントを登録する。
テスト環境(https://test.pypi.org/)もあるので、テストしたい時は、こちらも登録する

APIトークンの発行も忘れずに。

PyPIへの公開

$ pip install twine
# テスト環境で試したい場合
$ python3 -m twine upload --repository testpypi dist/*

# 本番環境
$ python -m twine upload dist/*

Discussion