LoginSignup
10
11

More than 5 years have passed since last update.

setuptoolsを使ったインストール時に任意の処理を実行する

Posted at

setuptoolsを使ってPythonパッケージを作る際、「install実行時に任意の場所にディレクトリをコピーする」ということができなくて1困ったので、強引にやってみた。

setup.py
# coding: utf-8
import setuptools
from setuptools.command.install import install
import shutil

# 標準のinstallコマンドを拡張
class my_install(install):
  description = "install myapp"

  # 自分の処理に必要なオプションを追加
  user_options = install.user_options + [
    ('my-data-dir=', 'd', "base directory for installing my data files." ),
  ]
  def initialize_options(self):
    self.my_data_dir = '/opt/myapp-data' # デフォルト値を設定
    install.initialize_options(self)

  def _pre_install(self):
    # やりたいことを書く
    shutil.copytree('./data',self.my_data_dir)

  def run(self):
    # 本来のinstall処理の実行前に自分のやりたい処理を挟む。
    self._pre_install()
    install.run(self)

  def get_outputs(self):
    # get_outputsは--recordオプション指定時に呼ばれ、install時に作成したファイルとディレクトリのリストを返す。
    # pip uninstall をした時に削除してほしいものがあれば、ここで返すようにする。
    return install.get_outputs(self) + [self.my_data_dir]

setuptools.setup(
  name='myapp',
  version='1.0',
  description='my python application',
  author='kokm',
  author_email='xxx@xxx',
  url='http://xxx.xxx/yyy',

  # installコマンドを自分のものに差し替える
  cmdclass={'install': my_install},
)

setuptools.command.installを好きなように拡張して、setup()cmdclassパラメータとして渡す。それだけ。
もちろん、install以外のコマンドも同様の方法で拡張できる。

実行方法

普通にsetup.pyを実行する。
追加したオプションは、setup.py install --helpの出力にもしっかり反映されている。

cd myapp
python setup.py install --my-data-dir=/opt/myapp-data

pipを使う場合は--install-optionを使わないと自分で追加したオプションが通らないので注意。

pip install --install-option='--my-data-dir=/opt/myapp-data' myapp-1.0.tar.gz
pip uninstall myapp

参考

1. ファイル単位のコピーならinstall_dataを使うことで可能。

10
11
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
10
11