How do you intercept a keyboard interrupt (CTRL-C)

2019-07-31 01:32发布

问题:

This is what I've tried...

from sun.misc import Signal
from sun.misc import SignalHandler

class InterruptHandler(SignalHandler):

    def handle(self):
        print "Shutting down server..."


Signal.handle(Signal("INT"),InterruptHandler())

It's based on this http://www.javaspecialists.co.za/archive/Issue043.html, but evidently I'm missing something.

回答1:

Looks like a bug in Jython. There are some workarounds given there.



回答2:

I was facing similar problem before. This is how I get it resolved.

First, register a signal handler in your Jython script by:

import signal
def intHandler(signum, frame):
    print "Shutting down.."
    System.exit(1)

# Set the signal handler
signal.signal(signal.SIGINT, intHandler)
signal.signal(signal.SIGTERM, intHandler)

This will register the signal handler for the Jython script to handle CTRL+C keyboard input.

However, the default console class org.python.util.JLineConsole treats ctrl+C as a normal character inputs.

So, Secondly - need to change the python.console to an alternative console class org.python.core.PlainConsole by either change the Jython property:

python.console=org.python.core.PlainConsole

or add the jvm argument:

-Dpython.console=org.python.core.PlainConsole

This will help you to shutdown the program after CTRL+C is pressed.