开发者

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

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜