Without version checking or `six`, how can I use `

2019-06-14 20:50发布

问题:

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.