如何检查哪个版本的Python解释器正在运行我的脚本?
当前回答
从命令行(注意大写的“V”):
python -V
这在“man python”中有记录。
从IPython控制台
!python -V
其他回答
只是为了好玩,下面是在CPython 1.0-3.7b2, Pypy, Jython和Micropython上的一种方法。在现代代码中,这更像是一种新奇的做法。我将其作为http://stromberg.dnsalias.org/~strombrg/pythons/的一部分编写,这是一个脚本,用于在多个版本的python上同时测试一段代码,因此您可以轻松地了解哪些python特性与哪些版本的python兼容:
via_platform = 0
check_sys = 0
via_sys_version_info = 0
via_sys_version = 0
test_sys = 0
try:
import platform
except (ImportError, NameError):
# We have no platform module - try to get the info via the sys module
check_sys = 1
if not check_sys:
if hasattr(platform, "python_version"):
via_platform = 1
else:
check_sys = 1
if check_sys:
try:
import sys
test_sys = 1
except (ImportError, NameError):
# just let via_sys_version_info and via_sys_version remain False - we have no sys module
pass
if test_sys:
if hasattr(sys, "version_info"):
via_sys_version_info = 1
elif hasattr(sys, "version"):
via_sys_version = 1
else:
# just let via_sys remain False
pass
if via_platform:
# This gives pretty good info, but is not available in older interpreters. Also, micropython has a
# platform module that does not really contain anything.
print(platform.python_version())
elif via_sys_version_info:
# This is compatible with some older interpreters, but does not give quite as much info.
print("%s.%s.%s" % sys.version_info[:3])
elif via_sys_version:
import string
# This is compatible with some older interpreters, but does not give quite as much info.
verbose_version = sys.version
version_list = string.split(verbose_version)
print(version_list[0])
else:
print("unknown")
有六个模块,你可以做到:
import six
if six.PY2:
# this is python2.x
else:
# six.PY3
# this is python3.x
from sys import version_info, api_version, version, hexversion
print(f"sys.version: {version}")
print(f"sys.api_version: {api_version}")
print(f"sys.version_info: {version_info}")
print(f"sys.hexversion: {hexversion}")
输出
sys。版本:3.6.5 (v3.6.5:f59c0932b4, march 28 2018, 17:00:18) [MSC .1900 64位(AMD64)] sys。api_version: 1013 sys。version_info: sys。Version_info (major=3, minor=6, micro=5, releaslevel ='final', serial=0) sys。hexversion: 50726384
已经有几个答案建议如何查询当前的python版本。为了以编程方式检查版本需求,我将使用以下两种方法之一:
# Method 1: (see krawyoti's answer)
import sys
assert(sys.version_info >= (2,6))
# Method 2:
import platform
from distutils.version import StrictVersion
assert(StrictVersion(platform.python_version()) >= "2.6")
对于windows,进入命令提示符并键入此命令以获取python版本:
python --version
Or
python -V
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行