如何在运行时检测 Python 版本? [英] How do I detect the Python version at runtime?

查看:60
本文介绍了如何在运行时检测 Python 版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 文件,它可能必须支持 Python 版本 <3.x 和 >= 3.x.有没有办法内省 Python 运行时以了解它运行的版本(例如,2.6 或 3.2.x)?

解决方案

好的,看看 sys.versionsys.version_info.

例如,要检查您是否正在运行 Python 3.x,请使用

导入系统如果 sys.version_info[0] <3:raise Exception("必须使用 Python 3")

这里,sys.version_info[0] 是主要版本号.sys.version_info[1] 会给你次要版本号.

在 Python 2.7 及更高版本中,sys.version_info 的组件也可以通过名称访问,因此主要版本号为 sys.version_info.major.>

另见 如何在使用新语言功能的程序中检查 Python 版本?

I have a Python file which might have to support Python versions < 3.x and >= 3.x. Is there a way to introspect the Python runtime to know the version which it is running (for example, 2.6 or 3.2.x)?

解决方案

Sure, take a look at sys.version and sys.version_info.

For example, to check that you are running Python 3.x, use

import sys
if sys.version_info[0] < 3:
    raise Exception("Must be using Python 3")

Here, sys.version_info[0] is the major version number. sys.version_info[1] would give you the minor version number.

In Python 2.7 and later, the components of sys.version_info can also be accessed by name, so the major version number is sys.version_info.major.

See also How can I check for Python version in a program that uses new language features?

这篇关于如何在运行时检测 Python 版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆