views:

44

answers:

4

I have a Python script that uses Python version 2.6 syntax (Except error as value:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that the user doesn't get hit with a nasty error, however, no matter where I place that code, it doesn't work. Once it hits the strange syntax it throws the syntax error, disregarding any attempts of mine of version checking.

I know I could simply place a try/except block over the area that the SyntaxError occurs and generate the message there but I am wondering if there is a more "elegant" way. As I am not very keen on placing try/except blocks all over my code to address the version issue. I looked into using an __ init__.py file, but the user won't be importing/using my code as a package, so I don't think that route will work, unless I am missing something... Thanks in advance.

Here is my version checking code:

import sys
def isPythonVersion(version):
    if float(sys.version[:3]) >= version:
        return True
    else:
        return False

if not isPythonVersion(2.6):
    print "You are running Python version", sys.version[:3], ", version 2.6 or 2.7 is required. Please update. Aborting..."
    exit()
A: 

In sys.version_info you will find the version information stored in a tuple:

sys.version_info
(2, 6, 6, 'final', 0)

Now you can compare:

def isPythonVersion(version):
    return version >= sys.version_info[0] + sys.version_info[1] / 10.
eumiro
Thanks but I already have a method of checking this, shown above.
Stunner
+2  A: 

Create a wrapper script that checks the version and calls your real script -- this gives you a chance to check the version before the interpreter tries to syntax-check the real script.

bstpierre
Yep, this did the trick. Thanks!
Stunner
A: 

If speed is not a priority, you can avoid this problem entirely by using sys.exc_info to grab the details of the last exception.

katrielalex
A: 

Something like this in beginning of code?

import sys
if sys.version_info<(2,6):
    raise SystemExit('Sorry, this code need Python 2.6 or higher')
Tony Veijalainen