Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 726
sorin Avatar asked Jun 03 '11 08:06

sorin


People also ask

How do I set Python to a specific version?

As a standard, it is recommended to use the python3 command or python3. 7 to select a specific version. The py.exe launcher will automatically select the most recent version of Python you've installed. You can also use commands like py -3.7 to select a particular version, or py --list to see which versions can be used.


2 Answers

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) 
like image 147
Arkady Avatar answered Oct 22 '22 08:10

Arkady


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 
like image 30
Walter Mundt Avatar answered Oct 22 '22 08:10

Walter Mundt