玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置: 玩蛇网首页 > 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 sys
if sys.version_info < (3, 4):
    raise RuntimeError('At least Python 3.4 is required')

玩蛇网文章,转载请注明出处和文章网址:http://www.iplaypy.com/wenda/wd20466.html [复制]



我要小额赞助,鼓励作者写出更好的教程↓↓↓

玩蛇网Python QQ群,欢迎加入: ① 279974227 玩蛇网Python新手群
修订日期:2017年05月24日 - 20时13分58秒 发布自玩蛇网

我要分享到:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules