【问题标题】:How do you intercept a keyboard interrupt (CTRL-C) in Jython?如何在 Jython 中拦截键盘中断 (CTRL-C)?
【发布时间】:2011-11-17 11:48:10
【问题描述】:

这是我尝试过的......

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())

它基于http://www.javaspecialists.co.za/archive/Issue043.html,但显然我遗漏了一些东西。

【问题讨论】:

  • 不管怎样,try catch 似乎也不起作用。看来python vm线程捕获的是中断而不是脚本。

标签: java jvm jython signal-handling


【解决方案1】:

Looks like a bug in Jython。那里提供了一些解决方法。

【讨论】:

    【解决方案2】:

    我以前也遇到过类似的问题。我就是这样解决的。

    首先,通过以下方式在您的 Jython 脚本中注册一个信号处理程序:

    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)
    

    这将为 Jython 脚本注册信号处理程序以处理 CTRL+C 键盘输入。

    但是,默认控制台类 org.python.util.JLineConsole 将 ctrl+C 视为普通字符输入。

    因此,其次 - 需要通过更改 Jython 属性将 python.console 更改为替代控制台类 org.python.core.PlainConsole:

    python.console=org.python.core.PlainConsole
    

    或添加 jvm 参数:

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

    这将帮助您在按下 CTRL+C 后关闭程序。

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 2010-11-16
      • 2014-10-04
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 2016-08-12
      相关资源
      最近更新 更多