【问题标题】:Handling SIGINT in parallel fabric task在并行结构任务中处理 SIGINT
【发布时间】:2013-08-01 17:57:31
【问题描述】:

我使用multiprocessing.Manager 来跟踪我在并行结构任务中创建的资源。如果出现问题,我经常想做一个ctrl-c 来停止任务,但是我仍然需要打印这些资源。

如何让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 隐藏信号,但似乎没有任何效果。

【问题讨论】:

    标签: python multithreading exception fabric


    【解决方案1】:

    看起来您正在使用 SIGTERM 而不是 SIGINT 调用 signal.signal。 CTRL-C 通常不会导致 SIGINT,而不是 SIGTERM? [1]

    我会尝试在 signal.signal() 中使用 SIGINT 而不是 SIGTERM。

    [1]https://en.wikipedia.org/wiki/Control-C

    【讨论】:

    • 哎呀,你是对的。我想我正在使用 SIGINT 但错误地将其复制到我的测试代码中。我用SIGINT更新了问题和一些示例输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多