【发布时间】:2016-01-11 09:40:44
【问题描述】:
我尝试编写一些代码来捕获 Broken Pipe 错误。代码应在 Python 2.x 和 Python 3.x 中运行。
在 Python 2.x 中,损坏的管道由 socket.error 表示
socket.error: [Errno 32] Broken pipe
这在 Python 3.x 中已更改 - 损坏的管道现在是 BrokenPipeError
BrokenPipeError: [Errno 32] Broken pipe
异常处理的语法也发生了一些变化(参见https://stackoverflow.com/a/34463112/263589),所以我需要做的是:
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。由于socket.error 在 Python 3.x 中已被弃用,在不久的将来 Python 3.x 中可能会出现类似的问题。
我可以怎样做才能让这段代码在 Python 2.x 和 Python 3.x 中运行?
【问题讨论】:
-
看看python-future.org/compatible_idioms.html,他们展示了异常处理。
-
谢谢!但是python-future.org/compatible_idioms.html#catching-exceptions 没有解释如何捕获 Python 2 或 Python 3 中不存在但在其他版本中是强制性的异常。
-
@RajarshiDas 这很有趣!如果建议 Python 忽略 SIGPIPE 错误,您是否想说根本不需要捕获损坏的管道?
标签: python python-3.x exception python-2.x