扭曲 - 通过 KeyboardInterrupt 中断回调

标签 twisted reactor keyboardinterrupt

我目前正在使用 Twisted 在回调中的 for 循环中重复一项任务,但是如果用户通过 Ctrl-C 发出 KeyboardInterrupt,我希望 react 器在回调(一个)中中断循环。根据我的测试, react 器仅在回调结束时停止或处理中断。

有没有什么方法可以在回调运行过程中将 KeyboardInterrupt 发送到回调或错误处理程序?

干杯,

克里斯

#!/usr/bin/env python

from twisted.internet import reactor, defer


def one(result):
    print "Start one()"
    for i in xrange(10000):
        print i
    print "End one()"
    reactor.stop()


def oneErrorHandler(failure):
    print failure
    print "INTERRUPTING one()"
    reactor.stop()    


if __name__ == '__main__':

    d = defer.Deferred()
    d.addCallback(one)
    d.addErrback(oneErrorHandler)
    reactor.callLater(1, d.callback, 'result')

    print "STARTING REACTOR..."
    try:
        reactor.run()
    except KeyboardInterrupt:
        print "Interrupted by keyboard. Exiting."
        reactor.stop()

最佳答案

这是有意避免(半)抢占,因为 Twisted 是一个协作多任务系统。 Ctrl-C 在 Python 中使用解释器在启动时安装的 SIGINT 处理程序进行处理。处理程序在调用时设置一个标志。执行完每个字节码后,解释器会检查标志。如果已设置,则此时会引发 KeyboardInterrupt。

react 器安装自己的 SIGINT 处理程序。这取代了解释器处理程序的行为。 react 器的处理程序启动 react 器关闭。由于它不会引发异常,因此不会中断正在运行的任何代码。循环(或其他)结束,当控制权返回到 react 堆时,关闭继续进行。

如果您希望 Ctrl-C(即 SIGINT)引发 KeyboardInterrupt,那么您可以使用信号模块恢复 Python 的 SIGINT 处理程序:

signal.signal(signal.SIGINT, signal.default_int_handler)

但是请注意,如果您在来自 Twisted 的代码(而不是您自己的应用程序代码)运行时发送 SIGINT,则行为未定义,因为 Twisted 不希望被 KeyboardInterrupt 中断。

关于扭曲 - 通过 KeyboardInterrupt 中断回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4125772/

相关文章:

python - 在多个进程中运行整个 Twisted 应用程序

reactor - Reactor 会提供远程处理吗?

spring - 获取环形缓冲区中当前的消息数

python - 在 PyPy 上运行 Scrapy

ssl - 扭曲的 listenSSL 虚拟主机

python - 停止 Twisted 吞下异常

java - 如何在 Spring 5 MVC 中将 FilePart 转换为 byte[]

Python 2.7 : Child thread not catching KeyboardInterrupt

汇编8086监听键盘中断