Without version checking or `six`, how can I use `except MyError, e:` vs `except MyError as e` to work with Python 2&3?

狂风中的少年 提交于 2019-12-08 15:38:31

问题


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

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?"

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 versions 2.6+:

except MyError as e
    #OR#
except MyError, e

Python 2.5-:

except MyError, e

A little background:

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.


回答1:


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]

This'll work on Python 1.5 and up.

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.



来源:https://stackoverflow.com/questions/32319317/without-version-checking-or-six-how-can-i-use-except-myerror-e-vs-except

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!