Search code examples
pythoncommand-lineargparsedocopt

How do I make a custom system command out of my Python program?


If I have a command-line program written in Python (specifically using docopt which uses argparse I think), and I want to run it as my-program command1 args instead of python my-program.py command1 args, what do I have to do? For now, this is for Debian-based OS (e.g Ubuntu).

I normally make my module a package so I already have setup.py but that doesn't grant me a free command.

Thanks!


EDIT

@pyrospade gave a very good link below. I am going to share my result.

Suppose we have

top-level-directory
    setup.py
    package/
         __init__.py
         cli.py

You can use scripts=['package/cli.py'] if you want to access cli.py in the shell.

If you want to run as my-cli, you can use

entry_points={
    'console_scripts':
        ['my-cli=package.cli:main']
}

Since I use docopt, I have this

def dispatcher(...)
def fun1(....)


def main():    
    arguments = docopt(COMMAND, version="xxxx")
    dispatcher(arguments)

if __name__ == '__main__':
    main()

You can even put it under __init__.py by saying ['my-cli=package:main'] but again, you need a function called main(). But you can name it whatever you want. Just saying.


Solution

  • Make sure your program has a shebang line at the top:

    #!/usr/bin/python
    

    Make the file executable:

    chmod a+x my-program.py
    

    Make a link with the desired command name:

    ln -s my-program.py /usr/local/bin/my-program