如何检查哪个版本的Python解释器正在运行我的脚本?
当前回答
已经有几个答案建议如何查询当前的python版本。为了以编程方式检查版本需求,我将使用以下两种方法之一:
# Method 1: (see krawyoti's answer)
import sys
assert(sys.version_info >= (2,6))
# Method 2:
import platform
from distutils.version import StrictVersion
assert(StrictVersion(platform.python_version()) >= "2.6")
其他回答
只是为了好玩,下面是在CPython 1.0-3.7b2, Pypy, Jython和Micropython上的一种方法。在现代代码中,这更像是一种新奇的做法。我将其作为http://stromberg.dnsalias.org/~strombrg/pythons/的一部分编写,这是一个脚本,用于在多个版本的python上同时测试一段代码,因此您可以轻松地了解哪些python特性与哪些版本的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")
更简单的方法:
在Spyder中,启动一个新的“IPython控制台”,然后运行任何现有的脚本。
现在版本可以在控制台窗口打印的第一个输出中看到:
“Python 3.7.3(默认,Apr 24 2019, 15:29:51)…”
就像Seth说的,主脚本可以检查sys。Version_info(但请注意,它直到2.0才出现,所以如果你想支持旧版本,你需要检查sys模块的另一个version属性)。
但是,您仍然需要注意不要在文件中使用旧版本Python中没有的任何Python语言特性。例如,这在Python 2.5及更高版本中是允许的:
try:
pass
except:
pass
finally:
pass
但在较旧的Python版本中不能工作,因为只能使用except OR最终匹配try。所以为了与旧版本的Python兼容,你需要写:
try:
try:
pass
except:
pass
finally:
pass
最简单的方法
只需在终端中输入python,就可以看到版本 就像下面这样
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.
>>>
对于windows,进入命令提示符并键入此命令以获取python版本:
python --version
Or
python -V
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录