How do I pass a parameter to the setuptools command from the install to build command?

I have a custom command build

with a custom option:

class BuildCommand(distutils.command.build.build):

    user_options = [('foo', None, 'Foo')]

      

added as follows:

setup(...
    cmdclass={"build": BuildCommand}
    ...)

      

Works well if i run python setup.py build --foo

. However, it is build

also called at startup install

or develop

, and so I would like these commands to have the same option and pass it to build. How can i do this?

+3


source to share


1 answer


I found two ways to do this (at least for setuptools

, haven't tried with raw distutils

), neither of which I particularly like, but they seem to work:



  • Use global options by replacing distclass

    :

    class FooDistribution(setuptools.Distribution):
        global_options = setuptools.Distribution.global_options + [
            ('foo', None, 'Foo'),
            ]
    
        def __init__(self, attrs=None):
            self.foo = 0
            super().__init__(attrs)
    
    setup(
        ...
        distclass=FooDistribution,
        ...
    )
    
          

    Then you can access it from command classes via self.distribution.foo

    . Parameters must be passed on the command line before the first command.

  • Add the parameter to all relevant command classes and use set_undefined_options

    in the assembly class:

    from distutils.command.build import build as build_orig
    from setuptools.command.install import install as install_orig
    from setuptools.command.develop import develop as develop_orig
    cmdclass = {}
    for super_class in [build_orig, install_orig, develop_orig]:
        class command(super_class):
            user_options = super_class.user_options + [
                ('foo', None, 'Foo'),
            ]
            def initialize_options(self):
                super().initialize_options()
                self.foo = None
    
        cmdclass[super_class.__name__] = command
    
    def run_build(self):
        print("self.foo: ", self.foo)
    
    def finalize_options_build(self):
        build_orig.finalize_options(self)
        for cmd in ['install', 'develop']:
            self.set_undefined_options(cmd,
                                       ('foo', 'foo'))
    
    cmdclass["build"].run = run_build
    cmdclass["build"].finalize_options = finalize_options_build
    
    setup(
        ...
        cmdclass=cmdclass
        ...
    )
    
          

0


source







All Articles