Python twisted not catching exception

185 views Asked by At

My main class is something like

# file bmdaemon.py
from txjsonrpc.web import jsonrpc
from twisted.web import server, xmlrpc
from twisted.internet import reactor, defer, threads, task
import xmlrpclib
from txjsonrpc.web.jsonrpc import Proxy


class BMDaemon(jsonrpc.JSONRPC):
    # class definition


class XmlRpcInterface(xmlrpc.XMLRPC):
     # class definition


if __name__ == "__main__":
    try:
        bm_daemon = BMDaemon()
        xml_interface = XmlRpcInterface()
        portJSONRPC = bm_daemon.get_listeningJSON_port()
        portXMLRPC = bm_daemon.get_listeningXML_port()
        reactor.listenTCP(portJSONRPC, server.Site(bm_daemon))
        reactor.listenTCP(portXMLRPC, server.Site(xml_interface))
        reactor.run()
    except KeyboardInterrupt:
        print "MAIN: ^C received, exiting."

And I'm just trying catching CTRL+C at the outer level, i.e. the "main" execution.

However, sending the mentioned keyboard interrupt just prints

<< prints from BMDaemon >>
^CUnhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
  File "bmdaemon.py", line 562, in <module>
    bm_daemon = BMDaemon()
  File "bmdaemon.py", line 114, in __init__
    << some line >>
  File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 170, in start
    self()
  File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 215, in __call__
    d = defer.maybeDeferred(self.f, *self.a, **self.kw)
--- <exception caught here> ---
  File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 134, in maybeDeferred
    result = f(*args, **kw)
  File "bmdaemon.py", line 519, in __registration
    << some line >>
  File "/usr/lib/python2.7/commands.py", line 60, in getstatusoutput
    text = pipe.read()
exceptions.KeyboardInterrupt: 
<< prints from XmlRpcInterface >>

In other words, I'm not catching the requested error ! Please be patient since I come from a Java environment where a situation like that would be much cleaner to understand.

1

There are 1 answers

0
MagunRa On BEST ANSWER

Have you tried a minimal example? Like this:

import time
def sleeper():
    while(True):
        print "So sleepy"
        time.sleep(1)

try:
    sleeper()
except KeyboardInterrupt:
    print "Ctrl-C"

This works for me (as I think you intend it). (I know this is more a comment, but I couldn't get the code to show up right)