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


当前回答

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

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

其他回答

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

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

该信息可在sys。sys模块中的版本字符串:

>>> import sys

人类可读的:

>>> print(sys.version)  # parentheses necessary in python 3.       
2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]

如需进一步处理,请使用sys。Version_info或sys.hexversion:

>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192

为了确保脚本以最小版本的Python解释器要求运行,在代码中添加以下内容:

assert sys.version_info >= (2, 5)

比较主要版本和次要版本信息。在元组中添加micro(= 0,1等)和releaselevel (='alpha','final'等)。然而,请注意,最好是“回避”检查是否有特定的功能,如果没有,就采取变通措施(或退出)。有时,新版本的特性会消失,被其他特性所取代。

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

import six

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

尝试使用os。Popen在变量中读取它:

import os
ver = os.popen('python -V').read().strip()
print(ver)