What to reference in the shebang python26 or python2.6
For a Python script I need a specific Python version. Now my installation of Python 2.6 contains both python26 and python2.6
Which one should I put in the shebang?
Option 1:
#!/usr/bin/env python2.6
Option 2:
#!/usr/bin/env python26
EDIT: Yes, there is a reason not to use plain python. In some of our environments in开发者_StackOverflow the university python is linked to python2.4 and my code uses quite some 2.6 features.
You can't always guarantee that the shebang will be used (or even that the user will have that version).
You shouldn't really limit to a specific version exactly. It's best to require at least a given version (if your code works on Python 2.6, why wouldn't it work on Python 2.7? I might not have Python 2.6 installed in a few months time.)
I would stick with the /usr/bin/env python
shebang and instead dynamically detect the version. Believe it or not, the "normal" way of doing this is:
import sys
ver = sys.version[:3]
That will give you a 3-character string such as "2.6" or "2.7". I would just check that the first character = '2' (assuming you want to prevent Python 3 from running your scripts, since it's largely incompatible) and the third character >= '6'.
Edit: See Petr's comment -- use sys.version_info[0:2]
instead (gives you a pair like (2, 6)
or (2, 7)
.
Just checked on my Linux system there is only python2.6
not python26
so the former looks better.
Just to clarify, I would use conditional imports instead, in my case I need OrderedDict
which is python 2.7+ only;
try:
from collections import OrderedDict
except ImportError:
print("Python 2.7+ is needed for this script.")
sys.exit(1)
Why don't you just use /usr/bin/python
instead? Is there any reason for not doing that?
If you don't have it already, you can create a link to it using this command:
ln -s /usr/bin/python26 /usr/bin/python
This ensures compatibility if you ever upgrade your python in the future.
精彩评论