LoginSignup
52
46

More than 5 years have passed since last update.

Pythonのモジュールをつくる

Last updated at Posted at 2015-04-12

nodeのパッケージシステムのように気軽に作ろうとしたら意外と面倒くさかったので。

プロジェクトの作成

適当なディレクトリを作る。

mkdir mymodule && cd $_

virtualenvかdirenvを使ってシステムのpythonとディレクトリ内のpythonを隔離する。

virtualenvの場合は virtualenv env
direnvの場合は direnv edit . してから開いたエディタで layout python とする。
pip freeze してwsgirefしか出なかったら環境構築は完了。
システムのpipとは隔離されているので必要なモジュールを自由にpip installしてよい。

ディレクトリ構成

.
├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── mymodule.py
├── setup.py
└── tests
    └── myplugin_test.py

.gitignore

Pythonの.gitignoreをベースに、virtualenvを使うならenvディレクトリを追加、direnvを使うなら.direnvを追加。
gitignore/Python.gitignore

README.md

本当はmarkdownではなくPyPIで整形して表示されるrestructuredTextの方がいい。

setup.py

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

from __future__ import with_statement
from setuptools import setup

with open("README.md") as f:
    long_description = f.read()

setup(
    name="mymodule",
    version="0.1.0",
    description="hogehoge.",
    long_description=long_description,
    author="yourid",
    author_email="youremail",
    url="yoururl",
    py_modules=["mymodule"],
    include_package_data=True,
    install_requires=["Flask"],
    tests_require=["nose"],
    license="MIT",
    keywords="",
    zip_safe=False,
    classifiers=[]
)

py_modules は公開するモジュールのファイル名を指定する。
install_requirestests_require は依存モジュールを書き出す。記事によってはpip freezeしたものをここに指定していることがあるが、バージョンまで指定されてしまいdependency hellっぽくなるので手動でバージョン指定せずに書くほうが良い。
classifiersここから選ぶ。

MANIFEST.in

デフォルトだとPythonのファイルしかモジュールに入れてくれないので、特別なテキストファイルとかを入れるためにはこれが必要。今回はREADME.mdを入れるために include README.md と書いておく。
requirements.txtとか用意するならそれもここに記述しておく必要がある。

mymodule.py

モジュール本体。適当に書く。

tests/

モジュールのテスト。適当に書く。ちゃんと書く。

テスト

noseを使う。pip install noseすれば入る。
実行はnosetests

PyPIとTest PyPIに登録

Test PyPIPyPIに登録。
ホームディレクトリに.pypircファイルを作って登録情報を書いておく。

[distutils]
index-servers =
    pypi
    pypitest

[pypi]
repository: https://pypi.python.org/pypi
username: {{ユーザーネーム}}
password: {{パスワード}}

[pypitest]
repository: https://testpypi.python.org/pypi
username: {{ユーザーネーム}}
password: {{パスワード}}

ひと通りモジュールができてテストも完了したら python setup.py register -r https://testpypi.python.org/pypiしてパッケージを登録した後python setup.py sdist upload -r https://testpypi.python.org/pypi でTest PyPIに登録される。テストサイトなのでどんどん登録テストしてよい。
問題なく登録されたら、pip install --index-url https://testpypi.python.org/simple/ mymoduleでインストールできるようになっている。
システムのPythonとかでちゃんとインストールできるか、importして使えるようになっているかなどのテストしてから本番PyPIに登録する。

python setup.py register で本番PyPIにモジュールの登録
python setup.py sdist upload で本番PyPIにモジュールのアップロードが出来る。

おわり

これをつくりました
airtoxin/plugin-loader

52
46
1

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
52
46