LoginSignup
38
25

More than 5 years have passed since last update.

GitHub のリポジトリを requirements.txt に含める

Last updated at Posted at 2016-10-19

概要

English
PyPI には登録されていないが,GitHub では公開されているライブラリを依存関係に含める方法.
また,setup.py から requirements.txt を参照している場合の対応方法について忘備録としてまとめる.

requirements.txt

GitHub リポジトリの URL が https://github.com/rgmining/common の場合,
requirements.txt には,

requirements.txt
-e git+https://github.com/rgmining/common.git#egg=rgmining_common-0.9.0

のように書く.#egg= 以降は <パッケージ名>-<バージョン> という書式にするようだ.
また,pip-tools を使って requirements.txt を生成している場合,
requirements.in には上記と同じ文字列を記入する.

setup.py

今まで,setup.py では下記のようにrequirements.txtの内容をinstall_requiresに渡していた.

setup.py
from setuptools import setup, find_packages

def load_requires_from_file(filepath):
    with open(filepath) as fp:
        return [pkg_name.strip() for pkg_name in fp.readlines()]

setup(
    # その他の項目は省略
    install_requires=load_requires_from_file("requirements.txt")
)

requirements.txtにURLが含まれている場合は,もう少し改良してパッケージ名だけをリストアップする.

setup.py
def take_package_name(name):
    if name.startswith("-e"):
        return name[name.find("=")+1:name.rfind("-")]
    else:
        return name.strip()

def load_requires_from_file(filepath):
    with open(filepath) as fp:
        return [take_package_name(pkg_name) for pkg_name in fp.readlines()]

また,URL部分はsetup関数のキーワード引数dependency_linkに渡す.

setup.py
def load_links_from_file(filepath):
    res = []
    with open(filepath) as fp:
        for pkg_name in fp.readlines():
            if pkg_name.startswith("-e"):
                res.append(pkg_name.split(" ")[1])
    return res

setup(
    # 他の項目は省略
    install_requires=load_requires_from_file("requirements.txt"),
    dependency_links=load_links_from_file("requirements.txt"),
)

以上で,python setup.py testなどとすると,GitHubからパッケージを用意してテストを実行できる.

参考

38
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
25