Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax

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...

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()
like image 697
Stunner Avatar asked Sep 21 '10 12:09

Stunner


People also ask

How do I fix invalid syntax error in Python?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

Why does Python keep saying invalid syntax?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.


1 Answers

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')
like image 113
Tony Veijalainen Avatar answered Nov 07 '22 00:11

Tony Veijalainen