I have a Python file which might have to support Python versions < 3.x and >= 3.x. Is there a way to introspect the Python runtime to know the version which it is running (for example, 2.6 or 3.2.x
)?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
To make the scripts compatible with Python2 and 3 i use :
Version check example below.
Note that I do not stop the execution, this snippet just:
- do nothing if exact version matches
- write INFO if revision (last number) is different
- write WARN if any of major+minor are different
Sure, take a look at
sys.version
andsys.version_info
.For example, to check that you are running Python 3.x, use
Here,
sys.version_info[0]
is the major version number.sys.version_info[1]
would give you the minor version number.In Python 2.7 and later, the components of
sys.version_info
can also be accessed by name, so the major version number issys.version_info.major
.See also How can I check for Python version in a program that uses new language features?
The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3,
six
is the compatibility module.six.PY2
andsix.PY3
are two booleans if you want to check the version.However, a better solution than using a lot of
if
statements is to usesix
compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax fornext
, someone could updatesix
so your old code would still work.http://pythonhosted.org/six/
Cheers
Try this code, this should work:
Just in case you want to see all of the gory details in human readable form, you can use:
Output for my system:
Something very detailed but machine parsable would be to get the
version_info
object fromplatform.sys
, instead, and then use its properties to take a predetermined course of action. For example:Output on my system: