简体   繁体   English

多个python版本的异常处理

[英]exception handling with multiple python versions

I am having a delicate problem with python exceptions. 我在使用python异常时遇到了一个微妙的问题。 My software is currently running on multiple platforms and I still aim at being compatible with py2.5 because it's on a cluster where changing versions will become major effort. 我的软件当前在多个平台上运行,并且我仍然旨在与py2.5兼容,因为它位于群集上,在该群集上更改版本将成为主要工作。

One of the (debian) systems was recently updated from 2.6 to 2.7, and some pieces of code throw weird exceptions from the underlying C parts. 其中一个(debian)系统最近从2.6更新到2.7,一些代码段引发了基础C部分的怪异异常。 However, this was never the case before and still is not the case on my mac 2.7 -> there's no bug in the code but rather with one of the new libraries. 但是,这从来没有过,在我的mac 2.7上仍然不是这种情况->代码中没有bug,而是使用了一个新库。

I figured how to manage the exception for 2.7, but the exception handling is unfortunately incompatible with 2.5. 我知道了如何管理2.7的异常,但是不幸的是,异常处理与2.5不兼容。

Is there a way to run something like "preprocessor commands - C style?" 有没有办法运行“预处理程序命令-C风格”之类的方法?

if interpreter.version == 2.5:
foo() 
elif interpreter.version == 2.7:
bar()

?

Cheers, El 欢呼声,埃尔

Example attached: 附带示例:

try:                                                                                                     
    foo()
except RuntimeError , (errorNumber,errorString):
    print 'a'
    #ok with 2.5, 2.7 however throws exceptions

try:                                                                                                     
    foo()
except RuntimeError as e:
    print 'a'
#ok with 2.7, 2.5 does not understand this

You can write two different try...except for two different versions basically for those mis match exception in two different versions. 您可以编写两个不同的try ...,除了两个不同版本外,基本上是针对两个不同版本中的那些不匹配异常。

import sys

if sys.version_info[:2] == (2, 7):
    try:
        pass
    except:
        # Use 2.7 compatible exception
        pass
elif sys.version_info[:2] == (2, 5):
    try:
        pass
    except:
        # Use 2.5 compatible exception
        pass

You can write your exception handler to be compatible with both python versions instead: 您可以编写异常处理程序以使其与两个 python版本兼容:

try:                                                                                                     
    foo()
except RuntimeError, e:
    errorNumber, errorString = e.args
    print 'a'

Demo: 演示:

>>> def foo():
...     raise RuntimeError('bar!')
... 
>>> try:
...     foo()
... except RuntimeError, e:
...     print e.args
... 
('bar!',)

There is no need to do Python version detection here, unless you need this to work across Python versions 2.5 through to 2.7 and Python 3.x. 此处无需执行Python版本检测,除非您需要此操作以跨Python 2.5至2.7和Python3.x。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM