1

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.

CppLearner
  • 15,082
  • 31
  • 106
  • 161

2 Answers2

2

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
bignose
  • 27,414
  • 13
  • 72
  • 104
pyrospade
  • 7,442
  • 2
  • 33
  • 51
0

Add the shebang (#!) and make it executable.

#! /usr/bin/python

Have a look here for more info.

ebarrenechea
  • 3,725
  • 1
  • 29
  • 37