How to write Python code that is able to properly require a minimal python version?

I would like to see if there is any way of requiring a minimal python version.

I have several python modules that are requiring Python 2.6 due to the new exception handling (as keyword).

It looks that even if I check the python version at the beginning of my script, the code will not run because the interpreter will fail inside the module, throwing an ugly system error instead of telling the user to use a newer python.


Solution 1:

You can take advantage of the fact that Python will do the right thing when comparing tuples:

#!/usr/bin/python
import sys
MIN_PYTHON = (2, 6)
if sys.version_info < MIN_PYTHON:
    sys.exit("Python %s.%s or later is required.\n" % MIN_PYTHON)

Solution 2:

You should not use any Python 2.6 features inside the script itself. Also, you must do your version check before importing any of the modules requiring a new Python version.

E.g. start your script like so:

#!/usr/bin/env python
import sys

if sys.version_info[0] != 2 or sys.version_info[1] < 6:
    print("This script requires Python version 2.6")
    sys.exit(1)

# rest of script, including real initial imports, here