如何检查哪个版本的Python解释器正在运行我的脚本?
当前回答
从stdlib中使用平台的python_version:
from platform import python_version
print(python_version())
# 3.9.2
其他回答
可以这样写:
#!/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甚至可能无法加载脚本,因此不会报告此错误。作为一种变通方法,您可以在一个脚本中运行上述操作,该脚本导入了更现代的代码。
下面是一个简短的命令行版本,它可以直接退出(方便脚本和自动执行):
python -c "print(__import__('sys').version)"
或者只是大调、小调和微调:
python -c "print(__import__('sys').version_info[:1])" # (2,)
python -c "print(__import__('sys').version_info[:2])" # (2, 7)
python -c "print(__import__('sys').version_info[:3])" # (2, 7, 6)
最简单的方法
只需在终端中输入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.
>>>
我喜欢系统。对于这样的东西。
>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True
你最好的选择可能是这样的:
>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
... print "Error, I need python 2.6"
... else:
... from my_module import twoPointSixCode
>>>
此外,您总是可以在一个简单的try中包装导入,这应该会捕获语法错误。而且,按照@Heikki的观点,这段代码将与更老版本的python兼容:
>>> try:
... from my_module import twoPointSixCode
... except Exception:
... print "can't import, probably because your python is too old!"
>>>
推荐文章
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置