自动检测当前运行环境版本的python方法是什么,运行环境python,搜关键词搜不准,都是搜到


搜关键词搜不准,都是搜到直接在shell环境下运行python -v,关键是我要在程序里用到版本信息做判断呢,该怎么写呢?

查下manual就可以知道了,有多个类似变量可用

sys.version A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use version_info and the functions provided by the platform module.

最『政治正确』的方式应该是sys.implementation。PEP0421是说这个问题的: http://www.python.org/dev/peps/pep-04...

The Problem With sys.(version|version_info|hexversion)
Earlier versions of this PEP made the mistake of calling sys.version_info (and friends) the version of the Python language, in contrast to the implementation. However, this is not the case. Instead, it is the version of the CPython implementation. Incidentally, the first two components of sys.version_info (major and minor) also reflect the version of the language definition.
As Barry Warsaw noted, the "semantics of sys.version_info have been sufficiently squishy in the past" [18]. With sys.implementation we have the opportunity to improve this situation by first establishing an explicit location for the version of the implementation.
This PEP makes no other effort to directly clarify the semantics of sys.version_info. Regardless, having an explicit version for the implementation will definitely help to clarify the distinction from the language version.

可惜这个PEP太新了…只有最新的CPython3.3才支持…orz…

如果是给人读,用 sys.version,
如果是给机器比较,用 sys.version_info,
如果是判断是不是 PyPy 等第三方实现,用 sys.implementation(要 Python 3.3)。

例子:

import sysif sys.version_info < (3, 4):    raise RuntimeError('At least Python 3.4 is required')

编橙之家文章,

评论关闭