Python: except EOFError: ... 不起作用
我有一个 try/ except 块,用于发送消息并等待客户端的确认。如果客户端终止,pickle 会引发 EOFError,但下面的代码不会捕获该错误并执行正常关闭。相反,它打印堆栈跟踪。我认为它与“除了socket.error,EOFError:”行有关 - 我是否使用错误的语法来处理socket.error和EOFError?
try:
msgs = [1]
self.sock.send(pickle.dumps(msgs))
rdy = pickle.loads(self.sock.recv(2097152))
except socket.error, EOFError:
print 'log socketmanager closing'
self.terminate()
break
I have a try/except block that sends a message and waits for confirmation from client. If the client terminates, pickle raises an EOFError, but the code below does not catch the error and execute the graceful shut down. It instead prints stack trace. I assume it has to do with the line "except socket.error, EOFError:" - am I using the wrong syntax to handle both socket.error and EOFError there?
try:
msgs = [1]
self.sock.send(pickle.dumps(msgs))
rdy = pickle.loads(self.sock.recv(2097152))
except socket.error, EOFError:
print 'log socketmanager closing'
self.terminate()
break
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Python 2.x 中,
except a, b
形式捕获a
类型的异常,并将其分配给名为b
的变量。在您的情况下,这将导致EOFError
被忽略。请尝试以下操作:编辑:详细说明一下,Python 3.0 中的新语法以及 2.6+ 中可用的新语法(尽管不是必需的)用于捕获异常的值是
except a as b
。In Python 2.x, the form
except a, b
catches an exception of typea
and assign it to a variable calledb
. In your case this would result inEOFError
being ignored. Try this instead:Edit: to elaborate, the new syntax in Python 3.0, and available, though not required, in 2.6+, for capturing the value of an exception is
except a as b
.break
导致错误,它只能在for
循环或try/finally
块中使用,不能在try/ except 中使用
,请参阅文档和更多。break
is causing the error, it can only be used inside afor
loop or atry/finally
block, nottry/except
, see docs and more.