webminal.org
webminal.org

Reputation: 47226

ways to execute 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

Upvotes: 6

Views: 645

Answers (2)

Khelben
Khelben

Reputation: 6461

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.

Upvotes: 2

Mike Mueller
Mike Mueller

Reputation: 2182

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.)

Upvotes: 17

Related Questions