无法使用Ctrl-C终止Python脚本 [英] Cannot kill Python script with Ctrl-C

查看:704
本文介绍了无法使用Ctrl-C终止Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本测试Python线程:

I am testing Python threading with the following script:

import threading

class FirstThread (threading.Thread):
    def run (self):
        while True:
            print 'first'

class SecondThread (threading.Thread):
    def run (self):
        while True:
            print 'second'

FirstThread().start()
SecondThread().start()

这是在Kubuntu 11.10上的Python 2.7中运行的. Ctrl + C 不会将其杀死.我还尝试为系统信号添加处理程序,但这没有帮助:

This is running in Python 2.7 on Kubuntu 11.10. Ctrl+C will not kill it. I also tried adding a handler for system signals, but that did not help:

import signal 
import sys
def signal_handler(signal, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

要杀死该进程,我会使用 Ctrl + Z 将程序发送到后台,然后通过PID杀死它,这不会被忽略.为什么这么持久地忽略 Ctrl + C ?我该如何解决?

To kill the process I am killing it by PID after sending the program to the background with Ctrl+Z, which isn't being ignored. Why is Ctrl+C being ignored so persistently? How can I resolve this?

推荐答案

Ctrl + C 终止主线程,但是由于您的线程不在守护程序模式下,他们继续运行,这使过程保持活力.我们可以使它们成为守护进程:

Ctrl+C terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
f.start()
s = SecondThread()
s.daemon = True
s.start()

但是,还有另一个问题-一旦主线程启动了线程,就没有别的事情了.因此它退出了,线程立即被销毁.因此,让主线程保持活动状态:

But then there's another problem - once the main thread has started your threads, there's nothing else for it to do. So it exits, and the threads are destroyed instantly. So let's keep the main thread alive:

import time
while True:
    time.sleep(1)

现在它将保留打印第一"和第二",直到您按 Ctrl + C .

Now it will keep print 'first' and 'second' until you hit Ctrl+C.

编辑:正如评论者所指出的,守护进程线程可能没有机会清理临时文件之类的东西.如果需要,请在主线程上捕获KeyboardInterrupt并协调其清理和关闭.但是在很多情况下,让守护线程突然死掉可能已经足够了.

as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

这篇关于无法使用Ctrl-C终止Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆