Verifying Python interpreter version after running Script with invalid syntax

I have a Python script that uses Python syntax version 2.6 (except for error as value :), which version 2.5 refers to. Therefore, in my script, I included some code to check the version of the Python interpreter before proceeding so that the user does not get an unpleasant error, however, no matter where I place this code, it does not work. When it gets into weird syntax, it throws a syntax error, not paying attention to any version checking attempts.

I know that I can just place the try / except block over the area in which SyntaxError is raised and throw a message there, but I wonder if there is a more β€œelegant” way. Since I'm not really trying to place try / except blocks all over my code to solve the version problem. I was looking for the use of the __ init__.py file, but the user will not import / use my code as a package, so I don’t think this route will work if I don’t miss something ...

Here is my version verification 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() 
+7
python interpreter
source share
4 answers

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

+7
source share

Something like this at the beginning of the code?

 import sys if sys.version_info<(2,6): raise SystemExit('Sorry, this code need Python 2.6 or higher') 
+7
source share

In sys.version_info you will find the version information stored in the 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. 
+3
source share

If speed is not a priority, you can completely avoid this problem by using sys.exc_info to get information about the last exception.

0
source share

All Articles