如何检查哪个版本的Python解释器正在运行我的脚本?


当前回答

这只返回2.7 3.6或3.9

import sys
current_version = ".".join(map(str, sys.version_info[0:2]))

这是你通常需要的…

其他回答

所有的答案都有深刻的见解

另一种方法是platform.python_version_tuple()

python3 -c “import platform; print(platform.python_version_tuple())”

(‘3’, ‘6’, ‘8’)

有六个模块,你可以做到:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x

我喜欢系统。对于这样的东西。

>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True

更简单的方法:

在Spyder中,启动一个新的“IPython控制台”,然后运行任何现有的脚本。

现在版本可以在控制台窗口打印的第一个输出中看到:

“Python 3.7.3(默认,Apr 24 2019, 15:29:51)…”

可以这样写:

#!/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)

在你的脚本顶部。

请注意,根据脚本中的其他内容,比目标版本更老的python甚至可能无法加载脚本,因此不会报告此错误。作为一种变通方法,您可以在一个脚本中运行上述操作,该脚本导入了更现代的代码。