How do I check what version of Python is running my script?
How can I check what version of the Python Interpreter is interpreting my script?
>>> import sys
>>> print(sys.version) # parentheses necessary in python 3. 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) # or >>> sys.hexversion 34014192
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
assert sys.version_info >= (2, 5)
This compares major and minor version information. Add micro (=
1, etc) and even releaselevel (=
'final', etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.
Read more... Read less...
From the command line (note the capital 'V'):
This is documented in 'man python'.
From IPython console
sys.hexversion for stuff like this.
>>> import sys >>> sys.hexversion 33883376 >>> '%x' % sys.hexversion '20504f0' >>> sys.hexversion < 0x02060000 True
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.
Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.