开发者

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

I have a Python script that uses Python version 2.6 syn开发者_如何学编程tax (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()


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.


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')


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜