Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 345
zfou Avatar asked Nov 17 '25 22:11

zfou


1 Answers

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
like image 183
falsetru Avatar answered Nov 19 '25 13:11

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!