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
Here's a short commandline version which exits straight away (handy for scripts and automated execution):
Or just the major, minor and micro:
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:
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.
Your 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:
Like Seth said, the main script could check
sys.version_info
(but note that that didn't appear until 2.0, so if you want to support older versions you would need to check another version property of the sys module).But you still need to take care of not using any Python language features in the file that are not available in older Python versions. For example, this is allowed in Python 2.5 and later:
but won't work in older Python versions, because you could only have except OR finally match the try. So for compatibility with older Python versions you need to write:
From the command line (note the capital 'V'):
This is documented in 'man python'.