Python: Best way to check for Python version in program that uses new language features?
Posted
by Mark Harrison
on Stack Overflow
See other posts from Stack Overflow
or by Mark Harrison
Published on 2009-01-15T08:45:28Z
Indexed on
2010/04/09
19:33 UTC
Read the original article
Hit count: 338
If I have a python script that requires at least a particular version of python, what is the correct way to fail gracefully when an earlier version of python is used to launch the script?
How do I get control early enough to issue an error message and exit?
For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of python.
update
I know how to check the version of python. The issue is that some syntax is illegal in older versions of python. Consider this program:
import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
When run under 2.4, I want this result
$ ~/bin/python2.4 tern.py
must use python2.5 or greater
and not this result:
$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
(channeling for a coworker)
© Stack Overflow or respective owner