Re: [問題] 請問如何在Pipe中處理KeyboardInterrupt
終於搞懂了,只是之前沒想清楚,這段 code 應該是這樣跑的
def run(rpipe):
try:
data = rpipe.recv()
exec(data)
except:
# 因為抓到 EOFError 而跑進來
# 之前被 block 的 KeyboardInterrupt 作用了
# 等同這邊寫了 raise KeyboardInterrupt
# 所以底下那行本來就執行不到 XD
print 'except'
finally:
print 'finally'
盲點在拿 Python 的想法去想執行順序,所以沒發現那空隙
實際上要抓到 KeyboardInterrupt 必須要再包一層 try ... except 才行
像這樣
def run(rpipe):
try:
try:
data = rpipe.recv()
exec(data)
except EOFError:
print '這一行永遠不可能執行到'
finally:
print 'EOFError finally'
except KeyboardInterrupt:
print 'KeyboardInterrupt'
finally:
print 'KeyboardInterrupt finally'
後遺症就是無法檢查是否產生過 EOFError
這問題應該在所有會 block interrupt 的函式上都有可能發生,不知道算不算 bug?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.41.140.104
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章