Last Updated: February 25, 2016
·
3.278K
· lukaszb

Custom subcommand at setup.py

It is sometimes useful to add custom command to our setup.py file - in example to make it possible to clone a project's repository and run python setup.py bootstrap and have our development environment configured.

In order to add a custom command we simply need to prepare a setuptools.Command subclass.
It has an user_options attribute that we need to define (setuptools requires it) and also some abstract methods we need to implement (or at least stub them): initialize_options and finalize_options. Finally, we can implement run method.

Here is simple example:

from setuptools import Command
from setuptools import find_packages
from setuptools import setup


class BootstrapEnvironmentCommand(Command):
    user_options = []

    def initialize_options(self):
        """Abstract method that is required to be overwritten"""

    def finalize_options(self):
        """Abstract method that is required to be overwritten"""

    def run(self):
        print(" => bootstrapping development environment ...")


setup(
    name='frogress',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[],
    cmdclass={'bootstrap': BootstrapEnvironmentCommand},
)

Now it is possible to run python setup.py bootstrap and while it doesn't do anything fancy (just prints out a line, as implemented at run method) we now have a good starting point to make it actually useful.