我目前正在使用 Twisted 在回调内的 for 循环中重复一项任务,但如果用户通过 Ctrl-C 发出 KeyboardInterrupt,我希望反应器在回调(一个)中中断循环。根据我的测试,反应器仅在回调结束时停止或处理中断。
有没有办法在回调运行过程中向回调或错误处理程序发送 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()