【问题标题】:exception handling with multiple python versions多个python版本的异常处理
【发布时间】:2013-07-01 19:14:09
【问题描述】:

我在 python 异常方面遇到了一个微妙的问题。 我的软件目前在多个平台上运行,我仍然致力于与 py2.5 兼容,因为它位于集群上,更改版本将成为主要工作。

其中一个(debian)系统最近从 2.6 更新到 2.7,一些代码从底层 C 部分抛出奇怪的异常。但是,以前从未出现过这种情况,并且在我的 mac 2.7 上仍然不是这种情况 -> 代码中没有错误,而是有一个新库。

我想出了如何管理 2.7 的异常,但不幸的是异常处理与 2.5 不兼容。

有没有办法运行“预处理器命令 - C 风格”之类的东西?

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

?

干杯, 埃尔

附上例子:

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

【问题讨论】:

    标签: python swing python-2.7 python-2.5


    【解决方案1】:

    您可以编写两个不同的尝试...除了两个不同的版本,基本上是针对两个不同版本中的不匹配异常。

    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
    

    【讨论】:

      【解决方案2】:

      您可以编写您的异常处理程序以与 两个 python 版本兼容:

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

      演示:

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

      这里不需要进行 Python 版本检测,除非您需要在 Python 版本 2.5 到 2.7 和 Python 3.x 之间工作。

      【讨论】: