1
我正在使用multiprocessing.Manager
來跟蹤我在並行結構任務中創建的資源。如果出現問題,我經常想要執行ctrl-c
來暫停任務,但是我仍然需要打印這些資源。在並行結構任務中處理SIGINT
我怎樣才能讓report_resources
總是退出前運行,並在下面的代碼正常工作:
from time import sleep
from multiprocessing import Manager
from fabric.utils import puts
from fabric.context_managers import hide,settings
from fabric.api import env,task,execute
from fabric.colors import green
import atexit
import signal
env.resources_log = Manager().list()
def report_resources(x=None,y=None):
if env.resources_log:
puts(green('we really really want to print these, no matter what happens'))
for r in env.resources_log:
puts(green('\t * '+str(r)))
atexit.register(report_resources)
signal.signal(signal.SIGINT, report_resources) # This doesn't work at catching ctrl-c in multiprocessing code
@task
def test():
def par_task():
env.resources_log.append("some resource")
puts('appended resource')
# HIT CTRL-C HERE
sleep(10)
puts('starting multithreading')
with settings(hide("running","stdout")
, hosts=['foo','bar']
, parallel=True):
execute(par_task)
如果我讓它運行我得到:
starting multithreading
[foo] appended resource
[bar] appended resource
Done.
we really really want to print these, no matter what happens
* some resource
* some resource
但是如果我CTRL- c在睡眠中我得到:
starting multithreading
[bar] appended resource
[foo] appended resource
^CTraceback (most recent call last):
File "/home/me/foo/lib/python2.7/site-packages/fabric/main.py", line 739, in main
[foo] we really really want to print these, no matter what happens
*args, **kwargs
...
... lots of garbage
我已經嘗試各種try
/catch
安排,隱藏信號與this method但似乎沒有奏效。
糟糕,你說得對。我想我正在使用SIGINT,但將其複製到我的測試代碼中是錯誤的。我已經用'SIGINT'更新了問題和一些示例輸出。 – jberryman