How can I check what version of the Python Interpreter is interpreting my script?
相关问题
- 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
sys.version_info
doesn't seem to return atuple
as of 3.7. Rather, it returns a special class, so all of the examples using tuples don't work, for me at least. Here's the output from a python console:I've found that using a combination of
sys.version_info.major
andsys.version_info.minor
seems to suffice. For example,...checks if you're running Python 3. You can even check for more specific versions with...
can check to see if you're running at least Python 3.5.
This information is available in the sys.version string in the sys module:
Human readable:
For further processing:
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
This compares major and minor version information. Add micro (=
0
,1
, etc) and even releaselevel (='alpha'
,'final'
, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.If you are working on linux just give command
python
output will be like thisYour best bet is probably something like so:
Additionally, you can always wrap your imports in a simple try, which should catch syntax errors. And, to @Heikki's point, this code will be compatible with much older versions of python:
Several answers already suggest how to query the current python version. To check programmatically the version requirements, I'd make use of one of the following two methods:
If you want to detect pre-Python 3 and don't want to import anything...
...you can (ab)use list comprehension scoping changes and do it in a single expression: