如果我有一个Python脚本,至少需要一个特定的 在Python版本中,优雅地失败的正确方式是什么 当使用早期版本的Python启动脚本时?

如何尽早获得控制权以发出错误消息 并退出吗?

For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.

我知道如何检查Python的版本。问题是一些语法在旧版本的Python中是非法的。考虑这个程序:

import sys
if sys.version_info < (2, 4):
    raise "must use python 2.5 or greater"
else:
    # syntax error in 2.4, ok in 2.5
    x = 1 if True else 2
    print x

当在2.4下运行时,我想要这个结果

$ ~/bin/python2.4 tern.py 
must use python 2.5 or greater

而不是这个结果:

$ ~/bin/python2.4 tern.py 
  File "tern.py", line 5
    x = 1 if True else 2
           ^
SyntaxError: invalid syntax

(为同事通灵。)


当前回答

如果用户使用Python 2 exe运行Python 3脚本,有一个简单的方法可以打印有用的消息:

把这作为第一行代码:

f' Error: This script requires Python 3.6 or later.'

它在Python 3.6+中什么都不做(当引入f-strings时),但在Python 2中编译失败,并在控制台上打印:

  File "test.py", line 34
    f' Error: Error: This script requires Python 3.6 or later.'
                                                                         ^
SyntaxError: invalid syntax

其他回答

进行版本比较的最好方法可能是使用sys.hexversion。这一点很重要,因为比较版本元组不会在所有python版本中都得到想要的结果。

import sys
if sys.hexversion < 0x02060000:
    print "yep!"
else:
    print "oops!"

Try

import platform
platform.python_version()

应该会给你一个像“2.3.1”的字符串。如果这不是你想要的,还有一组丰富的数据可以通过内置的“平台”获得。你想要的东西应该在里面。

集在Python 2.4中成为核心语言的一部分,以保持向后兼容。我当时就是这么做的,对你也有用:

if sys.version_info < (2, 4):
    from sets import Set as set
import sys
sys.version

会得到这样的答案吗

'2.7.6(默认,2016年10月26日,20:30:19)\n[GCC 4.8.4]'

这里是2.7.6版本

你可以使用eval进行测试:

try:
  eval("1 if True else 2")
except SyntaxError:
  # doesn't have ternary

此外,with在Python 2.5中可用,只需从__future__ import with_statement中添加。

编辑:为了尽早获得控制权,你可以将它分割成不同的.py文件,并在导入前检查主文件的兼容性(例如在包中的__init__.py中):

# __init__.py

# Check compatibility
try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

# import from another module
from impl import *