[問題] 請問如何在Pipe中處理KeyboardInterrupt
程式碼如下
# -*- coding: utf-8 -*-
from multiprocessing import Pipe, Process
def run(rpipe):
try:
data = rpipe.recv()
exec(data)
except:
print 'except' # 為什麼抓不到?
finally:
print 'finally'
if __name__=='__main__':
rpipe, wpipe = Pipe(False)
p = Process(target=run, args=(rpipe, ))
p.start()
try:
data = raw_input()
wpipe.send(data)
except KeyboardInterrupt:
wpipe.close()
p.join()
這程式是把使用者輸入的資料直接丟給 child process 執行
問題是,如果使用者按下 Ctrl-C,child process 那邊不知道要怎麼寫才能正確處理
本來的想法是,recv 中不能被中斷,所以 KeyboardInterrupt 會被擱置
然後 parent process 關閉 pipe 導致 recv 產生 EOFError
所以應該先處理 EOFError 再處理 KeyboardInterrupt。但實際執行結果如下
finally
Process Process-1:
Traceback (most recent call last):
File "C:\Python26\lib\multiprocessing\process.py", line 232, in _bootstrap
self.run()
File "C:\Python26\lib\multiprocessing\process.py", line 88, in run
self._target(*self._args, **self._kwargs)
File "C:\program_\test\m.py", line 5, in run
data = rpipe.recv()
KeyboardInterrupt
根本沒有任何 exception 被抓到就直接跳到 finally
然後不知道從哪邊丟出不知名錯誤和 KeyboardInterrupt
請問這到底是怎麼執行的?要怎麼寫才能正確動作?完全搞不懂...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.41.140.104
推
02/19 08:55, , 1F
02/19 08:55, 1F
→
02/19 09:03, , 2F
02/19 09:03, 2F
→
02/19 09:04, , 3F
02/19 09:04, 3F
→
02/19 09:06, , 4F
02/19 09:06, 4F
→
02/19 09:31, , 5F
02/19 09:31, 5F
→
02/19 10:09, , 6F
02/19 10:09, 6F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章