没有版本检查或“六”,我如何使用除MyError之外的除了MyError,e:`vs`,除了MyError作为e`与Python 2和3一起使用? [英] Without version checking or `six`, how can I use `except MyError, e:` vs `except MyError as e` to work with Python 2&3?

查看:171
本文介绍了没有版本检查或“六”,我如何使用除MyError之外的除了MyError,e:`vs`,除了MyError作为e`与Python 2和3一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,而不必检查所使用的Python版本。

I'm looking for a way to do this without checking for the Python version used.

请参阅如何编写与Python 2和Python 3兼容的异常处理代码?,有关这方面的细节,因为这个问题扩展了一个。

Please refer to How to write exception reraising code that's compatible with both Python 2 and Python 3? for details about this, since this question extends that one.

基本上,我可以将其概括为如果基于方法的异常引发基于语言的异常怎么办?

Basically, I can generalize this as, "What if the method-based exception raises a language-based exception?"

根据 Python尝试...除了逗号和'as '除了,下面显示了Python 3和Python 2的正确语法:

According to Python try...except comma vs 'as' in except, the following show the right syntax for Python 3 and Python 2:

Python 3:

except MyError as e

Python 2,for版本2.6+:

Python 2, for versions 2.6+:

except MyError as e
    #OR#
except MyError, e

Python 2.5-:

Python 2.5-:

except MyError, e

有一点背景:

我有一个粘性的情况,脚本将需要在许多古老的Linux机器上运行,其中将使用各种不同的Python版本,包括Python 2.5。

I have a sticky situation in which a script will need to be run on many an ancient Linux machine, in which a variety of different Python versions, including Python 2.5, will be used.

不幸的是,我必须将它分发为一个单一的大小有限的文件,这对我可以做多少进口产生一些限制。

Unfortunately, I have to distribute this as a single, size limited file, which puts some constraints on how much importing I can do.

此外,我对这些情况感兴趣,其中一个可能会误导其版本,或者可以使用的代码,而不必检查版本。当然,这可以解决。

Also, I'm interested in the case in which one of these may misreport its version, or in code that can be used without necessarily checking for a version. This could be worked around, though, of course.

推荐答案

您唯一的选择是避免异常分配,并将其从 sys.exc_info()功能

Your only option is to avoid the exception assignment and pull it out of the result for the sys.exc_info() function instead:

try:
    # ...
except Exception:  # note, no ", e" or "as e"
    import sys
    e = sys.exc_info()[1]

这将适用于Python 1.5及更高版本。

This'll work on Python 1.5 and up.

但是,您可能会遇到其他不兼容性和困难;编写polyglot的Python代码(适用于Python 2.x和3.x的代码)只能在Python 2.6和更高版本上才可行。

However, you'll likely to encounter other incompatibilities and difficulties; writing polyglot Python code (code that works on both Python 2.x and 3.x) is only really workable on Python 2.6 and up.

这篇关于没有版本检查或“六”,我如何使用除MyError之外的除了MyError,e:`vs`,除了MyError作为e`与Python 2和3一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆