0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pipで独自ライブラリをインストールする

Last updated at Posted at 2021-02-16

pipでインストールしたい

独自ライブラリのモジュールのパスを追加して開発を行っていた。


# 現在のディレクトリの絶対パスを取得
current_dir = pathlib.Path(__file__).resolve().parent
print(current_dir)
parent_dir = pathlib.Path(current_dir).resolve().parent
print(parent_dir)
# モジュールのあるパスを追加
sys.path.append(str(parent_dir))
from dokuji.dokuji.test import test as t

pythonだけで動かす場合には問題なかったのだが、この状態からpyinstallerを用いてexe化して実行した際に「(独自モジュール)が存在しない」とのメッセージが発生してしまった。
これはimportで取り込んだ際にpipなどでモジュール管理していないため関連ライブラリも取り込めず、エラーが起きてしまうのかな…と思った。
解決策として開発プロジェクト内に上記のモジュールを追加する方法もあるが、重複管理となってしまうため、それは避けたい。

setup.pyとrequirements.txtを作成

pipでインストールするために、setup.pyとrequirements.txtを作成した。

setup.py
import os, sys
from setuptools import setup, find_packages

sys.path.append('./tests')

def read_requirements():
    """Parse requirements from requirements.txt."""
    reqs_path = os.path.join('.', 'requirements.txt')
    #print(reqs_path)
    with open(reqs_path, 'r', encoding="utf-8") as f:
        requirements = [line.rstrip() for line in f]
    return requirements

# パッケージの依存情報、バージョン情報、パッケージ名を記述
setuptools.setup(
    name='dokuji name',   # パッケージ名
    version='0.0.1',    # 現在のバージョン名
    Description='独自ライブラリ',    # パッケージ概要
    author='製作者',
    author_email='xxxx@dokuji.co.jp',
    install_requires=read_requirements(),
    packages=find_packages(include=['dokuji','dokuji.*','bin']),
    include_package_data=True,
    package_dir={'dokuji':'dokuji'},
    python_requires=">=3.6",
)

独自モジュールと開発プロジェクトの配置は以下の通りとする

(root)
├ dokuji(ライブラリフォルダ)/
    - dokuji(ソースフォルダ)
├ sample_prj(プロジェクトフォルダ)/

以下の通り行うことで、ライブラリのインストールが可能。


> .\[newenvname]\Scripts\activate
# => venvを有効化
  
 newenvname > pip install ..\dokuji
# => インストール

newenvname > pip uninstall dokuji
# => アンインストール

これにより、以下の記述のみで参照が可能となる。

from dokuji.test import test as t
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?