Check If Python Version Is Compatible With Script Before Executing
I have a Python script that has been written using in Python 2.7. However it will be deployed to a number of different servers, some of which are running Python 2.4. In this case I
Solution 1:
sys.version_info[0]
is the major version only. So, it'll be 2
for all python 2.x versions. You're looking for sys.version_info[1]
, with the minor version:
# check for python 2if sys.version_info[0] != 2:
raise Exception("Please use Python 2")
# check for 2.7+if sys.version_info[1] < 7:
raise Exception("Please use Python 2.7+")
Alternatively, for more descriptive naming, you can use sys.version_info.major
instead of sys.version_info[0]
and sys.version_info.minor
instead of sys.version_info[1]
.
Also, make sure you add this near the top of your script so there are no incompatibilities before the line is hit and the exception is raised.
If your code uses incompatible syntax, then you should put the non-version checking code in a main function in a separate file, then import that after the check so that Python doesn't try to parse it.
Post a Comment for "Check If Python Version Is Compatible With Script Before Executing"