相关疑难解决方法(0)

捕获Ctrl + C/SIGINT并在python中正常退出多进程

如何在多进程python程序中捕获Ctrl + C并优雅地退出所有进程,我需要解决方案在unix和windows上工作.我尝试过以下方法:

import multiprocessing
import time
import signal
import sys

jobs = []

def worker():
    signal.signal(signal.SIGINT, signal_handler)
    while(True):
        time.sleep(1.1234)
        print "Working..."

def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    # for p in jobs:
    #     p.terminate()
    sys.exit(0)

if __name__ == "__main__":
    for i in range(50):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()
Run Code Online (Sandbox Code Playgroud)

它有点工作,但我不认为这是正确的解决方案.

编辑: 这可能与重复

python signals multiprocessing

77
推荐指数
3
解决办法
6万
查看次数

无法在命令提示符中捕获KeyboardInterrupt两次?

今天,当我注意到一些奇怪的东西时,我必须检查我的脚本如何在Windows命令提示符[1]上运行.我正在研究类似的东西,但这足以证明这个问题.这是代码.

def bing():
    try:
        raw_input()
    except KeyboardInterrupt:
        print 'This is what actually happened here!'

try:                     # pardon me for those weird strings
    bing()               # as it's consistent with everything in the chat room (see below)
    print 'Yoo hoo...'
except KeyboardInterrupt:
    print 'Nothing happens here too!'
Run Code Online (Sandbox Code Playgroud)

这是情况.当脚本运行时,它等待输入,并且用户应该按Ctrl+ C来引发一个KeyboardInterrupt(应该)被except内部块捕获的内容bing().所以,这应该是实际的输出.而且,当我在我的Ubuntu终端和IDLE(在Windows和Ubuntu上)运行它时会发生这种情况.

This is what actually happened here!
Yoo hoo...
Run Code Online (Sandbox Code Playgroud)

但是,这不会在Windows命令提示符下按预期方式进行.我宁愿得到一个奇怪的输出.

This is what actually happened here! Nothing happens here too!
Run Code Online (Sandbox Code Playgroud)

它看起来像是KeyboardInterrupt在整个程序中传播并最终终止它. …

python windows cmd exception-handling

16
推荐指数
1
解决办法
3897
查看次数