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
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
.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With