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


当前回答

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

import six

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

其他回答

import sys
sys.version.split(' ')[0]

sys。版本给你你想要的,只是选择第一个数字:)

可以这样写:

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

在Windows操作系统下,通过在命令提示符中输入以下命令,验证命令的Python版本

c:\>python -V
Python 2.7.16

c:\>py -2 -V
Python 2.7.16

c:\>py -3 -V
Python 3.7.3

此外,要查看每个Python版本的文件夹配置,请运行以下命令:

For Python 2,'py -2 -m site'
For Python 3,'py -3 -m site'

从stdlib中使用平台的python_version:

from platform import python_version
print(python_version())

# 3.9.2

要从命令行检查,在一个命令中,但包括major, minor, micro version, releaslevel和serial,然后调用与你的脚本使用的相同的Python解释器(即相同的路径):

> path/to/your/python -c "import sys; print('{}.{}.{}-{}-{}'.format(*sys.version_info))"

3.7.6-final-0

注意:.format()而不是f-strings或'.'.join()允许您使用任意格式和分隔符字符,例如,使其成为一个可greppable的单字字符串。我把它放在bash实用程序脚本中,报告所有重要的版本:python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++等。对日志记录、可复制性、故障排除和错误报告等很有用。