Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ways to execute python

Tags:

python

So far to execute a Python program, I'm using

> python file.py

I want to run the Python script simply using file name, like

> file.py 

similar to shell scripts like

> sh file.sh
> chmod +x file.sh
> ./file.sh 

or move file.sh to bin and then run

> file.sh
like image 746
webminal.org Avatar asked Mar 24 '10 09:03

webminal.org


2 Answers

Put this at the top of your Python script:

#!/usr/bin/env python

The #! part is called a shebang, and the env command will simply locate python on your $PATH and execute the script through it. You could hard-code the path to the python interpreter, too, but calling /usr/bin/env is a little more flexible. (For instance, if you're using virtualenv, that python interpreter will be found on your $PATH.)

like image 162
Mike Mueller Avatar answered Nov 07 '22 18:11

Mike Mueller


You ca also target the specific location of the python interpreter you wan to use, if you need to specify it (e.g, you're using different versions) Just add to the shebang line (the one starting with #!) the complete path of the interpreter you wan to use, for example

#!/home/user/python2.6/bin/python

But, in general, is better just to take the default using /usr/bin/env, as Mike says, as you don't have to rely on a particular path.

like image 26
Khelben Avatar answered Nov 07 '22 20:11

Khelben