[問題] 請問如何在Pipe中處理KeyboardInterrupt

看板Python作者 (allstar)時間13年前 (2012/02/19 07:10), 編輯推噓1(105)
留言6則, 2人參與, 最新討論串1/2 (看更多)
程式碼如下 # -*- 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
exeception是raw_input丟出來的... , 然後被except KbI接到
02/19 08:55, 1F

02/19 09:03, , 2F
KeyboardInterrupt在parent process跟child process都會產生
02/19 09:03, 2F

02/19 09:04, , 3F
raw_input()那個是parent process的,有抓到沒錯阿
02/19 09:04, 3F

02/19 09:06, , 4F
現在問題是child process那邊的動作很奇怪,不知道怎辦
02/19 09:06, 4F

02/19 09:31, , 5F
這我沒用過multiprocess這個module, 不太想去trace它...
02/19 09:31, 5F

02/19 10:09, , 6F
看起來像是你的process,還沒開始跑就被keyboard interrupt了
02/19 10:09, 6F
文章代碼(AID): #1FG2_tsA (Python)
文章代碼(AID): #1FG2_tsA (Python)