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

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(),但随后需要处理一些正则表达式。

也许有更优雅的方法。

其他回答

你可以使用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 *

我认为最好的方法是测试功能而不是版本。在某些情况下,这是微不足道的,但在另一些情况下并非如此。

eg:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

只要你在使用try/except块时足够具体,你就可以覆盖大部分基础。

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

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...

尽管问题是 我如何尽早获得控制以发出错误消息并退出?

我回答的问题是: 我如何获得足够早的控制,在启动应用程序之前发出错误消息?

我的回答和其他帖子有很大不同。 到目前为止,似乎答案都试图从Python内部解决你的问题。

我建议,在启动Python之前进行版本检查。我知道你的路径是Linux或unix。 但是我只能给你一个Windows脚本。我认为使它适应linux脚本语法不会太难。

下面是2.7版的DOS脚本:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

这不会运行应用程序的任何部分,因此不会引发Python异常。它不创建任何临时文件或添加任何操作系统环境变量。它不会因为不同的版本语法规则而导致应用程序出现异常。这样就少了三个安全入口。

FOR /F行是关键。

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

对于多个python版本,请检查url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17

我的hack版本是:

[女士脚本;Python模块启动前检查Python版本 http://pastebin.com/aAuJ91FQ

Try

import platform
platform.python_version()

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