graceful version detection?
donod at home.com
Mon Jun 18 03:53:04 CEST 2001
Ben Collins-Sussman wrote:
> Please excuse me if this is a common newbie question; I didn't find it
> in the FAQ or tutorial.
> If I write a python script that uses 2.X features, and then run it with
> a 1.X interpreter, I get a bunch of exceptions. Presumably this happens
> during the initial byte-compilation.
> I'd like the script to instead gracefully print:
> "Sorry, this program requires Python 2.0 or higher."
> I tried writing some code to do this by parsing `sys.version' at the top
> of my program; but as I said, the byte-compiler seems to choke first.
> What's the correct solution?
sys.version is a human readable string
>>> import sys
'2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)]'
This would require some fancy regular expression matching to extract
the version number in the most general case.
But, sys.version_info (new in ver 2.0) is a tuple which makes it
easy to test the version number:
(2, 1, 0, 'final', 0)
Since tuples are compared element by element, left to right, for
(at most) the length of the shorter operand, here's what I do:
if sys.version_info < (2, 1):
print "Sorry, this program requires Python version 2.1 or
if sys.version_info < (1, 5, 2):
You can also use sys.hexversion, but trying to express the version
numbers in hex and remembering how many hex digits are needed is more
trouble than it's worth.
Check the Library Reference for the sys module for these and a lot of
other system goodies.
More information about the Python-list