如果您真的非常想专门捕获 Cc,那么您可以以 Python 应用程序的通常方式执行此操作 - 使用signal.signal
安装一个处理程序来SIGINT
执行您想做的任何事情。如果您从处理程序调用任何 Twisted API,请确保使用,reactor.callFromThread
因为几乎所有其他 Twisted API 对于从信号处理程序调用都是不安全的。
However, if you're really just interested in inserting some shutdown-time cleanup code, then you probably want to use IService.stopService
(or the mechanism in terms of which it is implemented,reactor.addSystemEventTrigger
) instead.
If you're using twistd
, then using IService.stopService
is easy. You already have an Application
object with at least one service attached to it. You can add another one with a custom stopService
method that does your shutdown work. The method is allowed to return a Deferred
. If it does, then the shutdown process is paused until that Deferred
fires. This lets you clean up your connections nicely, even if that involves some more network (or any other asynchronous) operations.
If you're not using twistd
, then using reactor.addSystemEventTrigger
directly is probably easier. You can install a before shutdown trigger which will get called in the same circumstance IService.stopService
would have been called. This trigger (just any callable object) can also return a Deferred
to delay shutdown. This is done with a call to reactor.addSystemEventTrigger('before', 'shutdown', callable)
(sometime before shutdown is initiated, so that it's already registered whenever shutdown does happen).
service.tac gives an example of creating and using a custom service.
wxacceptance.py gives an example of using addSystemEventTrigger
and delaying shutdown by (an arbitrary) three seconds.
Both of these mechanisms will give you notification whenever the reactor is stopping. This may be due to a C-c keystroke, or it may be because someone used kill -INT ...
, or it may be because somewhere reactor.stop()
was called. They all lead to reactor shutdown, and reactor shutdown always processes shutdown event triggers.