0

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 am happy for the script to simply not run on the servers running Python 2.4. Is there a way I can do this in my Python script or would it be best to put a wrapper around the script?

I have tried doing this:

if sys.version_info[0] < 2.7:
    raise Exception("Python 2.7 or a more recent version is required.")

However because Python compiles the code before running it fails during compile when it hits part of the script that does not work in 2.4.

3
  • 3
    What about just not deploying to the servers that don't support Python 2.7? Commented Jan 5, 2021 at 13:51
  • 3
    Does this answer your question? How do I check what version of Python is running my script? Commented Jan 5, 2021 at 13:59
  • Your servers are in desperate need of an upgrade. Very strong advice to upgrade to Python 3.6+. Python 2.7 reached EOL one year ago, and Python 2.4 .. well, far too long ago. Commented Jan 5, 2021 at 14:00

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.