How can I check what version of the Python Interpreter is interpretting my script?
This information is available in the sys module:
>>> import sys
Human readable:
>>> print sys.version
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
For further processing:
>>> sys.version_info
(2, 5, 2, 'final', 0)
import sys
sys.version.split(' ')[0]
sys.version gives you what you want, just pick the first number :)
Your best bet is probably something like so:
>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
... print "Error, I need python 2.6"
... else:
... from my_module import twoPointSixCode
>>>
Additionally, you can always wrap your imports in a simple try, which should catch syntax errors. And, to @Heikki's point, this code will be compatible with much older versions of python:
>>> try:
... from my_module import twoPointSixCode
... except Exception:
... print "can't import, probably because your python is too old!"
>>>
Put something like:
#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
sys.stderr.write("You need python 2.6 or later to run this script\n")
exit(1)
at the top of your script.
Like Seth said, the main script could check sys.versio_info (but note that that didn't appear until 2.0, so if you want to support older versions you would need to check another version property of the sys module).
But you still need to take care of not using any Python language features in the file that are not available in older Python versions. For example, this is allowed in Python 2.5 and later:
try:
pass
except:
pass
finally:
pass
but won't work in older Python versions, because you could only have except OR finally match the try. So for compatibility with older Python versions you need to write:
try:
try:
pass
except:
pass
finally:
pass
I like sys.hexversion
for stuff like this.
http://docs.python.org/library/sys.html#sys.hexversion
>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True