Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Python 2.6+ script that gracefully fails with older Python?

I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.

from __future__ import print_function

import sys
if sys.hexversion < 0x02060000:
    raise Exception("py too old")

...
print("x",end=" ") # fails to compile with py24

How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?

like image 459
sorin Avatar asked Jun 14 '10 08:06

sorin


1 Answers

The easy method for Python 2.6 is just to add a line like:

b'You need Python 2.6 or later.'

at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.

like image 148
Scott Griffiths Avatar answered Nov 09 '22 22:11

Scott Griffiths