如果我有一个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

(为同事通灵。)


当前回答

将以下内容放在文件的最上方:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

然后继续使用正常的Python代码:

import ...
import ...
other code...

其他回答

为您的程序提供以下包装器。

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

如果您打算遇到使用2.0以前版本的Python解释器的人,那么还可以考虑使用sys.version(),但随后需要处理一些正则表达式。

也许有更优雅的方法。

import sys
sys.version

会得到这样的答案吗

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

这里是2.7.6版本

问题很简单。您检查了版本是否小于2.4,而不是小于或等于。因此,如果Python版本是2.4,则不小于2.4。 你应该拥有的是:

    if sys.version_info **<=** (2, 4):

,而不是

    if sys.version_info < (2, 4):

Try

import platform
platform.python_version()

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

我正在扩展akhan的出色回答,它甚至在编译Python脚本之前就打印了有用的消息。

如果你想确保脚本在Python 3.6或更新版本中运行,请在Python脚本顶部添加这两行:

#!/bin/sh
''''python3 -c 'import sys; sys.exit(sys.version_info < (3, 6))' && exec python3 -u -- "$0" ${1+"$@"}; echo 'This script requires Python 3.6 or newer.'; exit 1 # '''

(注意:第二行以四个单引号开始,以三个单引号结束。这看起来可能很奇怪,但这不是打字错误。)

这种解决方案的优点是,如果使用的是3.6以上的Python版本,像print(f' hello, {name}!')这样的代码不会引起SyntaxError。你会看到这条有用的信息:

This script requires Python 3.6 or newer.

当然,此解决方案仅适用于类unix的shell,并且仅适用于直接调用脚本(例如:./script.py),并设置了适当的eXecute权限位。