Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 ternary 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 syntax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.

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 running under 2.4, I want this result

$ ~/bin/python2.4 tern.py 

must use python 2.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

1 Answer

0 votes
by (106k points)

To check for Python version in a program that uses new language features you can test using eval:

try: 

eval("1 if True else 2") 

except SyntaxError: 

# doesn't have a ternary

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Apr 5, 2020 in BI by Vaibhav Ameta (17.6k points)
0 votes
1 answer

Browse Categories

...