Search code examples
pythonmultithreadingcmdtwisted

Using Cmd module inside a Python Twisted thread


Refering to this so question, i need to run a Cmd console application that will use Python's Twisted framework for network queries, with the following example:

from cmd import Cmd
from twisted.internet import reactor

class CommandProcessor(Cmd):
    def do_quit(self, line):
        print 'bye bye !'
        return True

    def do_hello(self, line):
        print 'world'

if __name__ == "__main__":
    reactor.callInThread(CommandProcessor().cmdloop)
    reactor.run()

Everything is finely working, but when executing quit command, the console hangs till i hit Ctrl+c, and same if i hit Ctrl+c before executing quit, the console also hangs till i execute quit command.

It seems the reactor is still working when i exit from the CommandProcessor().cmdloop, if it's the issue, i need a way to stop the reactor whenever my thread end.


Solution

  • Call reactor.stop to terminate twisted event loop. CommandProcess.do_quit is run in a separated thread; reactor.stop should be called using reactor.callFromThread


    Add reactor.callFromThread(reactor.stop) in do_quit method.

    def do_quit(self, line):
        print 'bye bye !'
        reactor.stop() # <------
        return True