distutils: How to pass a user defined parameter to setup.py?

前端 未结 8 988
温柔的废话
温柔的废话 2020-11-30 21:32

Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils\' setup.py script. I want to write a setup.py

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 22:20

    Perhaps you are an unseasoned programmer like me that still struggled after reading all the answers above. Thus, you might find another example potentially helpful (and to address the comments in previous answers about entering the command line arguments):

    class RunClientCommand(Command):
        """
        A command class to runs the client GUI.
        """
    
        description = "runs client gui"
    
        # The format is (long option, short option, description).
        user_options = [
            ('socket=', None, 'The socket of the server to connect (e.g. '127.0.0.1:8000')',
        ]
    
        def initialize_options(self):
            """
            Sets the default value for the server socket.
    
            The method is responsible for setting default values for
            all the options that the command supports.
    
            Option dependencies should not be set here.
            """
            self.socket = '127.0.0.1:8000'
    
        def finalize_options(self):
            """
            Overriding a required abstract method.
    
            The method is responsible for setting and checking the 
            final values and option dependencies for all the options 
            just before the method run is executed.
    
            In practice, this is where the values are assigned and verified.
            """
            pass
    
        def run(self):
            """
            Semantically, runs 'python src/client/view.py SERVER_SOCKET' on the
            command line.
            """
            print(self.socket)
            errno = subprocess.call([sys.executable, 'src/client/view.py ' + self.socket])
            if errno != 0:
                raise SystemExit("Unable to run client GUI!")
    

    setup(
        # Some other omitted details
        cmdclass={
            'runClient': RunClientCommand,
        },
    

    The above is tested and from some code I wrote. I have also included slightly more detailed docstrings to make things easier to understand.

    As for the command line: python setup.py runClient --socket=127.0.0.1:7777. A quick double check using print statements shows that indeed the correct argument is picked up by the run method.

    Other resources I found useful (more and more examples):

    Custom distutils commands

    https://seasonofcode.com/posts/how-to-add-custom-build-steps-and-commands-to-setuppy.html

提交回复
热议问题