To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
assert sys.version_info >= (2, 5)
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.
>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
... print "Error, I need python 2.6"
... else:
... from my_module import twoPointSixCode
>>>
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:
>>> try:
... from my_module import twoPointSixCode
... except Exception:
... print "can't import, probably because your python is too old!"
>>>
#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
sys.stderr.write("You need python 2.6 or later to run this script\n")
exit(1)
at the top of your script.
Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won’t get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.
Just type python in your terminal and you can see the version
as like following
desktop:~$ python
Python 2.7.6 (default, Jun 22 2015, 18:00:18)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
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:
try:
pass
except:
pass
finally:
pass
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:
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:
via_platform =0
check_sys =0
via_sys_version_info =0
via_sys_version =0
test_sys =0try:import platform
except(ImportError,NameError):# We have no platform module - try to get the info via the sys module
check_sys =1ifnot check_sys:if hasattr(platform,"python_version"):
via_platform =1else:
check_sys =1if check_sys:try:import sys
test_sys =1except(ImportError,NameError):# just let via_sys_version_info and via_sys_version remain False - we have no sys modulepassif test_sys:if hasattr(sys,"version_info"):
via_sys_version_info =1elif hasattr(sys,"version"):
via_sys_version =1else:# just let via_sys remain Falsepassif via_platform:# This gives pretty good info, but is not available in older interpreters. Also, micropython has a# platform module that does not really contain anything.print(platform.python_version())elif via_sys_version_info:# This is compatible with some older interpreters, but does not give quite as much info.print("%s.%s.%s"% sys.version_info[:3])elif via_sys_version:import string
# This is compatible with some older interpreters, but does not give quite as much info.
verbose_version = sys.version
version_list = string.split(verbose_version)print(version_list[0])else:print("unknown")
Just for fun, the following is a way of doing it on CPython 1.0-3.7b2, Pypy, Jython and Micropython. This is more of a curiosity than a way of doing it in modern code. I wrote it as part of http://stromberg.dnsalias.org/~strombrg/pythons/ , which is a script for testing a snippet of code on many versions of python at once, so you can easily get a feel for what python features are compatible with what versions of python:
via_platform = 0
check_sys = 0
via_sys_version_info = 0
via_sys_version = 0
test_sys = 0
try:
import platform
except (ImportError, NameError):
# We have no platform module - try to get the info via the sys module
check_sys = 1
if not check_sys:
if hasattr(platform, "python_version"):
via_platform = 1
else:
check_sys = 1
if check_sys:
try:
import sys
test_sys = 1
except (ImportError, NameError):
# just let via_sys_version_info and via_sys_version remain False - we have no sys module
pass
if test_sys:
if hasattr(sys, "version_info"):
via_sys_version_info = 1
elif hasattr(sys, "version"):
via_sys_version = 1
else:
# just let via_sys remain False
pass
if via_platform:
# This gives pretty good info, but is not available in older interpreters. Also, micropython has a
# platform module that does not really contain anything.
print(platform.python_version())
elif via_sys_version_info:
# This is compatible with some older interpreters, but does not give quite as much info.
print("%s.%s.%s" % sys.version_info[:3])
elif via_sys_version:
import string
# This is compatible with some older interpreters, but does not give quite as much info.
verbose_version = sys.version
version_list = string.split(verbose_version)
print(version_list[0])
else:
print("unknown")
sys.version_info doesn’t seem to return a tuple 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:
注意:.format()代替f字符串,或者'.'.join()允许您使用任意格式和分隔符char,例如,使其成为可抓握的单字字符串。我将其放在报告所有重要版本的bash实用程序脚本中:python,numpy,pandas,sklearn,MacOS,xcode,clang,brew,conda,anaconda,gcc / g ++等。对于日志记录,可复制性,故障排除报告等很有用。
Note: .format() instead of f-strings or '.'.join() allows you to use arbitrary formatting and separator chars, e.g. to make this a greppable one-word string. I put this inside a bash utility script that reports all important versions: python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++ etc. Useful for logging, replicability, troubleshootingm bug-reporting etc.