Skip to content

Instantly share code, notes, and snippets.

@3panda
Last active February 5, 2024 08:23
Show Gist options
  • Select an option

  • Save 3panda/7508508a89bd1ea1990217142eaf3c9c to your computer and use it in GitHub Desktop.

Select an option

Save 3panda/7508508a89bd1ea1990217142eaf3c9c to your computer and use it in GitHub Desktop.
Python 自作モジュールのパッケージ化

Python 自作モジュールのパッケージ化

Pythonで作られた自作のモジュールのパッケージ化について調べました。

ゴール

自作ライブラリをProjectのフォルダーの中に入れずに利用できるようにする

前提条件

  • Python 3.0以上

ディレクトリ構造

今回の解説のディレクトリ構造はこちらです。

|--sample_project
|  |--sample
|  |  |--sample.py
|  |  |--hoge.py
|  |--setup.py
| --test
|  |--test.py

setup.pyについて

「setup.py」はパッケージをインストール (アンインストール)です。 また細かな設定を記述します。

以下はとりあえずの「setup.py」のコードです。 ※実際に使う場合はちゃんと調べて書いた方が良さそうなので要調査

setup.py

from setuptools import setup, find_packages

setup(
    name='Sample',
    version="0.0.1",
    description="Sample Code",
    long_description="",
    author='sampleman',
    license='MIT',
    classifiers=[
        "Development Status :: 1 - Planning"
    ]
)

参考

SampleのPythonファイル

解説用のサンプルコードなのでどちらもシンプルな構造にしています。

sample.py

class Sample:
    def sample(self):
        print('sample')

hoge.py

class Hoge:
    def hoge(self):
        print('hoge')

パッケージのinstallとuninstall

パッケージをインストール方法

install

setup.pyのあるディレクトリで以下を実行

python setup.py develop

pip listで確認すると

pip list

他のモジュールと同様にインストールが確認出来る

Sample                             0.0.1      /xxxx/xxxx/sample_project

uninstall

アンインストールする場合はこちらを実行

python setup.py develop -u

確認

test/test.pyは以下のようなコードに なっています。

test.py

test/test.pyを以下のようにします。

from sample.sample import Sample
from sample.hoge import Hoge

sample = Sample()
sample.sample()

hoge = Hoge()
hoge.hoge()

インストール後に「test/test.py」を実行

python test.py

結果は以下の通り

sample
hoge

自作のモジュールをpipでインストールしたモジュールと同様に扱えます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment