0

I have a python project with multiple files and a cmd.py which uses argparse to parse the arguments, in the other files there are critical functions. What I want to do is: I want to make it so that if in the command line I were to put cmd -p hello.txt it runs that python file.

I was thinking that I could just simply move the cmd.py file to somewhere like /usr/bin/ or some other directory included in the $PATH, however since I have other files which work with my cmd.py, there will be multiple files in my /usr/bin.

Another thing that I could do is to make a symbolic link between the cmd.py and /usr/bin/cmd like this: ln -s /path/to/cmd.py /usr/bin/cmd, but then where do i put the cmd.py? and is this best practice?

Note: I intend for this to work on Linux and MacOS X, not windows

2
  • There may be a little primarily opinion based. You can put this cmd.py, with all the peripherals inside /usr/bin, or better /usr/local/bin, or create a separated folder inside /usr/bin or somewhere you wish then add it into $PATH environment variable. Commented Feb 14, 2019 at 5:48
  • 1
    I generally use a ~/bin. Commented Feb 14, 2019 at 6:00

3 Answers 3

2

The usual way to do this is to define a set of entry points in setup.py and let the packaging infrastructure do the heavy lifting for you.

setup(
    # ...
    entry_points = {
        'console_scripts': ['cmd = cmd:main'],
    }
)

This requires setuptools.

Here is some documentation for this facility: https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html

Sign up to request clarification or add additional context in comments.

Comments

1

For one thing I don't recommend installation in /usr/bin as that's where system programs go. /usr/local/bin or another custom directory added to $PATH could be appropriate.

As for getting it to run like a typical program, name it cmd, wherever you put it, as the extension is not necessary, and add this line to the top of the program:

#!/usr/bin/env python

(You may want to specify python3 instead of just python if you want to ensure Python 3.x is used.)

Then it can be made executable with chmod +x <path to your program>. Ensure that you have the necessary privileges to do this (i.e. sudo may be necessary).

Comments

1
  1. You can add a folder to your path.
    • in .bashrc add following
    • export PATH=[New_Folder_Path]:$PATH
  2. put the python program in your path_folder created at step 1.
  3. make it executable : chmod u+x [filename]
  4. open a new terminal, and you should be able to call the python program
  5. NOTE: make sure to put the shebang in your python-file : #!/usr/bin/env python3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.