Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scripts in /usr/bin

I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?

For example, instead of running

python htswap.py args

from the directory where it currently is, I want to be able to cd to any directory and do

htswap args

Thanks in advance!

like image 470
Steve Gattuso Avatar asked Jul 22 '09 20:07

Steve Gattuso


People also ask

What is python in usr bin?

By specifying #!/usr/bin/python you specify exactly which interpreter will be used to run the script on a particular system. This is the hardcoded path to the python interpreter for that particular system. The advantage of this line is that you can use a specific python version to run your code.

How do I start every python script?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

The first line of the file should be

#!/usr/bin/env python

You should remove the .py extension, and make the file executable, using

chmod ugo+x htswap

EDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)

like image 44
Michiel Buddingh Avatar answered Oct 15 '22 16:10

Michiel Buddingh


Simply strip off the .py extension by renaming the file. Then, you have to put the following line at the top of your file:

#!/usr/bin/env python

env is a little program that sets up the environment so that the right python interpreter is executed.

You also have to make your file executable, with the command

chmod a+x htswap

And dump it into /usr/local/bin. This is cleaner than /usr/bin, because the contents of that directory are usually managed by the operating system.

like image 101
Thomas Avatar answered Oct 15 '22 17:10

Thomas