graceful version detection?
Don O'Donnell
donod at home.com
Sun Jun 17 21:53:04 EDT 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?
>
Ben,
sys.version is a human readable string
>>> import sys
>>> sys.version
'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:
>>> sys.version_info
(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
higher."
sys.exit(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.
Good luck,
-Don
More information about the Python-list
mailing list