[PYTHON] Perform arbitrary processing during installation using setuptools

When creating a Python package using setuptools, I was in trouble [1](# 1) </ sub> because I couldn't "copy the directory to an arbitrary location when executing install", so I forced it. I tried it.

setup.py


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

#Extend the standard install command
class my_install(install):
  description = "install myapp"
  
  #Add options required for your processing
  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' #Set default value
    install.initialize_options(self)

  def _pre_install(self):
    #Write what you want to do
    shutil.copytree('./data',self.my_data_dir)

  def run(self):
    #Insert the process you want to do before executing the original install process.
    self._pre_install()
    install.run(self)

  def get_outputs(self):
    # get_outputs is--Called when the record option is specified, it returns a list of files and directories created during installation.
    #If there is something you want to remove when you do pip uninstall, return it here.
    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',

  #Replace the install command with yours
  cmdclass={'install': my_install},
)

Extend setuptools.command.install as you like and pass it as the cmdclass parameter of setup (). that's all. Of course, commands other than install can be extended in the same way.

Execution method

Run setup.py normally. The options you add are reflected in the output of setup.py install --help.

python


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

When using pip, please note that the options you added will not pass unless you use --install-option.

python


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

reference

http://pythoninside.com/en/source-code/2.7.5/distutils/command/install.py

1. You can use install_data to copy files.

Recommended Posts

Perform arbitrary processing during installation using setuptools
Periodically perform arbitrary processing with Python Twisted