Search code examples
pythonpython-3.xcommand-line-interface

How do I turn a Python program into a CLI without having to type python3 to execute?


Instead of typing

$ python3 Program.py -<flags> arguments, etc

I want to be able to DL the git clone and then be able to type

$ Program -<flags> arguments, etc 
# program name without the .py extension

I've seen other programs have .yaml files, req.txt files and dockerized them but I can't find anything that shows me how to do this. All the tutorials and guides have stopped short of how to make them simple command line programs.

I've done all the argparse, etc but I'm looking for a guide or some instruction of how to run it without having to nav to the dest folder


Solution

  • If you're thinking about distributing the program, you should probably add CLI entry points in your package's setup.py file.

    For example:

    Project structure

    ROOT/
    - setup.py
    - src/
        - program.py
    

    src/program.py

    # program.py
    
    def main():
        pass
    

    setup.py

    # setup.py
    
    from setuptools import find_packages, setup
    
    setup(
        name='my_program',
        version='1.0.0',
        packages=find_packages(),
        entry_points={
            'console_scripts': [
                'Program=src.program:main'
            ]
        }
    )
    

    The important bit is the line 'Program=src.program:main': it associates the name Program (the name to invoke from the command line) with the function main of src/program.py.

    Note that this name could be anything - it doesn't necessarily need to be related to your package name, python file names, etc.

    You can perform a local installation of your package in order to test this.

    From the ROOT directory, type $ pip install -e . Afterwards, typing

    $ Program
    

    in the terminal from any directory will execute the main function from src/program.py.

    This behaviour is the same if anyone pip installs your package over PyPI, instead of your local installation.