I am using a module that can only be found in python 2.7, so when I run my script I have to specify python2.7 script
instead of just script
. I know there are bigger issues out there, but still I was wondering -
is it possible, when writing a python script, to set the interpreter to 2.7 by default?
Maybe by setting #! /usr/bin/env python
for example?

- 9,789
- 13
- 47
- 68
-
Not if you run it with `python script`, though yes if you run it with `./script` – David Robinson Sep 11 '12 at 16:48
-
Highly depends on your system. – Sep 11 '12 at 16:48
3 Answers
Most unix environments will have the python2.7
executable, such that you can write:
#!/usr/bin/env python2.7
Obviously this doesn't help much on windows. You can also at least check the python version once you are started, although it won't help you run the later version if it is available:
import sys
print sys.version_info
...really do checks here...

- 30,415
- 7
- 59
- 78
Using the shebang is an appropriate way to specify this, yes. Find out where python2.7
is in your PATH using which python2.7
. This is e.g. /usr/bin/python2.7
. You then set the shebang:
#!/usr/bin/python2.7
Of course, this only works on those systems where Python 2.7 is available at this location :) This will also work on may systems: /usr/bin/env python2.7
Then make the script executable and fire it off using $ ./wonderful_python_script.py
.

- 33,287
- 14
- 85
- 130
If you are using Windows, install Python 3.3, which features a new launcher that provides shebang support under Windows. This will give you a (finally!) sane and cross-platform way of explicitly specifying interpreter versions.

- 14,354
- 6
- 37
- 50