我试图编写一些代码来捕获“Broken Pipe”错误。该代码应在Python 2.x和Python 3.x中运行。
在Python 2.x中,一个“Broken Pipe”错误被表示为socket.error
socket.error: [Errno 32] Broken pipe
这在Python 3.x中已经改变 - 现在一个断开的管道是一个BrokenPipeError
BrokenPipeError: [Errno 32] Broken pipe
同时,异常处理的语法有些变化(请参见https://dev59.com/QpLea4cB1Zd3GeqP12qT#34463112)。因此,我需要做的是:
try:
do_something()
except BrokenPipeError as e: # implies Python 3.x
resolve_for_python2()
except socket.error as e:
if sys.version_info[0] == 2: # this is necessary, as in Python >=3.3
# socket.error is an alias of OSError
# https://docs.python.org/3/library/socket.html#socket.error
resolve_for_python3()
else:
raise
目前(至少)还存在一个问题:在 Python 2.x 中没有BrokenPipeError
,因此每当 do_something()
中出现异常时,Python 2.x 将抛出另一个异常并且抱怨它不知道BrokenPipeError
。由于在 Python 3.x 中socket.error
被弃用,所以在不久的将来可能会出现类似的问题。
我该怎么做才能让这段代码在 Python 2.x 和 Python 3.x 中运行?