LoginSignup
27
25

More than 5 years have passed since last update.

【Python】自作モジュールをパッケージ化して配布する

Last updated at Posted at 2016-06-08

なにこれ

チームで開発してる時に、自作ツールをほかの人に使ってもらいたかったり、プロジェクトに自作モジュールを組み込みたいみたいなケースありますよね。そういう時、「パッケージ化」が便利っす。

プライベートリポジトリにおいてこっそりパッケージをホスティングする方法はあとで書きます。

(追記)
ごめんこれうごかんかも

準備

プロジェクトの構造

これからの説明は以下の様な構造を想定して書きます。
requirements関係は、pip freezeとかで吐き出してください。
プロジェクト名は「uhouhoapp」とします

  • setup.py
  • uhouhoapp/
    • main.py
    • sub.py
    • aaaa.py
  • requirements.txt
  • test-requirements.txt

手順

main.pyの例


def main():
    print('HelloWorld')

setup.pyの用意


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup, find_packages


def _load_requires_from_file(filepath):
    return [pkg_name.rstrip('\r\n') for pkg_name in open(filepath).readlines()]


def _install_requires():
    requires = _load_requires_from_file('requirements.txt')
    return requires


def _test_requires():
    test_requires = _load_requires_from_file('test-requirements.txt')
    return test_requires


def _packages():
    return find_packages(
        exclude=[
            '*.tests',
            '*.tests.*',
            'tests.*',
            'tests',
            '*.yaml'
        ],
    )


if __name__ == '__main__':
    description = ''
    setup(
        name='uhouhoapp',
        version='1.0.0',
        description=description,
        author='UhoUho Inc.',
        author_email='dev@uhouho.com',
        classifiers=[
            'Programming Language :: Python :: 2',
            'Programming Language :: Python :: 2.7',
            'Development Status :: 3 - Alpha',
            'License :: Confidencial',
            'Intended Audience :: Developers',
            'Natural Language :: English',
            'Operating System :: POSIX'
        ],
        packages=_packages(),
        install_requires=_install_requires(),
        tests_require=_test_requires(),
        test_suite='nose.collector',
        include_package_data=True,
        zip_safe=False,
        entry_points="""
        [console_scripts]
        uhouhoapp = uhouhoapp.main:main
        """,
    )

つかうとき

以下のコマンドを叩くと、おれおれモジュールが登録されます。


$ pip install -e .
Obtaining file:///Users/hiroyuki/test22
Installing collected packages: uhouhoapp
  Running setup.py develop for uhouhoapp
Successfully installed uhouhoapp-1.0.0

コマンドとして実行

実行させたいときは、以下のようなかんじ。
別にコマンドいいやって人は、setup.pyのconsole_scripts部分をけそう。

$ uhouhoapp
HelloWorld
27
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
27
25