gitを用いてpipでpythonのパッケージを配布する方法


前置き

pipとは

省略

インストール時のコマンド

pip install git+[URL]

[URL]にはインストールしたいgitのレポジトリのURLが入る。

pip install git+https://github.com/username/poyo.git

branchを指定してinstallしたい場合

pip install git+https://github.com/username/poyo.git@poyo

アップグレード時のコマンド

pip install git+[URL] -U

ファイル構成

repositoryName
|--topDirectory
|  |--bottomDirectory
|  |  |--bottom.py
|  |  `--__init__.py
|  |--top.py
|  `--__init__.py
`--setup.py

setup.py

このファイルはパッケージの名前などのメタデータ、コマンドとそのコマンドのPathを記述するものである。

メタデータ

メタデータには以下の種類がある。

メタデータ 説明
name パッケージ名 短い文字列
version リリースのバージョン 短い文字列
author パッケージ作者名 短い文字列
author_email パッケージ作者の電子メールアドレス 電子メールアドレス
maintainer パッケージメンテナンス担当者の名前 短い文字列
maintainer_email パッケージメンテナンス担当者の電子メールアドレス 電子メールアドレス
url パッケージのホームページ URL
description パッケージについての簡潔な概要説明 短い文字列
long_description パッケージについての詳細な説明 長い文字列
download_url パッケージをダウンロードできる場所 URL
classifiers 分類語のリスト 文字列からなるリスト
platforms プラットフォームのリスト 文字列からなるリスト
license パッケージのライセンス 短い文字列

この表は公式ドキュメントからコピペしたものである。
公式ドキュメント:https://docs.python.jp/3/distutils/setupscript.html

これらのメタデータは何も指定しなくても問題なく配布はできるが、nameとversionの指定は推奨されている。
これらは指定されていないとき、nameはUNKNOWN、versionは0.0.0が設定される。

実行コマンドとPath

entry_pointを指定することで実行コマンドを実行できるようになる。
entry_pointの指定の例を示す。

entry_points = {
    'console_scripts': [
            'top = topDirectory.top:main',
            'bottom = topDirectory.bottomDirectory.bottom:sub'
        ]
    }

entry_pointsに指定するものはdict型であり、実行コマンドを指定するためには'console_scripts'のkeyに対して、stringの配列のvalueを設定する。
実行コマンドとなるものは=の左辺であり、そのPathは=の右辺である。
=の右辺のうち:の左側がmoduleのPathであり、:の右側は:に最も近いmodule(以下最終moduleと呼ぶ)に含まれる関数名である。
ターミナル上で=の左辺の実行コマンドを実行すると、最終moduleに含まれる関数を実行する。
最終module名と実行コマンドの名前は一致していなければならない。

entry_pointsの他にpackagesも指定しなければならない。
packagesの例を示す。

packages = ["topDirectory", "topDirectory.bottomDirectory"]

packagesに含まれるものはentry_pointsで指定した=の右辺から最終module以下を除いたものである。

下にsetup.pyの例を示す。

setup.py
from setuptools import setup

setup(
    name = 'Hoge',
    version = '1.0.0',
    url = 'https://github.com/username/hoge.git',
    license = 'Free',
    author = 'Me',
    author_email = '[email protected]',
    description = 'Hoge',
    install_requires = ['setuptools'],
    packages = ["topDirectory", "topDirectory.bottomDirectory"],
    entry_points = {
        'console_scripts': [
            'top = topDirectory.top:main',
            'bottom = topDirectory.bottomDirectory.bottom:sub'
        ]
    }
)

__init__.py

空白で良い

top.py, bottom.py

実際のコードが入る。

top.py
def main():
    print("I am so happy")

if __name__ == '__main__':
    main()

結論

ファイルを一つ作るだけなため、gitを用いずにpipで配布するよりは楽。

参考

pip で github のリポジトリをインストール - Qiita
https://docs.python.jp/3/distutils/setupscript.html