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

孤街浪徒 提交于 2019-12-12 23:02:09

问题


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.



来源:https://stackoverflow.com/questions/7424722/how-do-you-intercept-a-keyboard-interrupt-ctrl-c-in-jython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!