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


当前回答

可以这样写:

#!/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甚至可能无法加载脚本,因此不会报告此错误。作为一种变通方法,您可以在一个脚本中运行上述操作,该脚本导入了更现代的代码。

其他回答

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

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

检查Python版本:Python -V或Python——version或apt-cache policy Python

你也可以运行whereis python查看安装了多少个版本。

这只返回2.7 3.6或3.9

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

这是你通常需要的…

如果你想检测python 3之前的版本,但不想导入任何东西…

...你可以(ab)使用列表理解范围的变化,并在一个表达式中完成:

is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)

最简单的方法

只需在终端中输入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.
>>>