3

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.

Community
  • 1
  • 1
zfou
  • 891
  • 1
  • 10
  • 33

1 Answers1

2

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Even with *reactor.stop()* the problem is still, typing quit will not get you of the console, it will hang till i hit Ctrl+c. – zfou Dec 26 '13 at 14:20
  • @FouratZOUARI, It worked for me. (at least in window 7, python 2.7.6 64bit) – falsetru Dec 26 '13 at 15:30
  • 2
    @FouratZOUARI, What happend if you replace `reactor.stop()` with `reactor.callFromThread(reactor.stop)` or `reactor.callLater(0, reactor.stop)` ? – falsetru Dec 26 '13 at 16:33
  • It is working, using twisted 12.3 **CommandProcessor** methods are already inside a thread since i started with **reactor.callInThread(CommandProcessor().cmdloop)**, so why should i call the stop explicitly from a thread ? – zfou Dec 26 '13 at 19:13
  • @FouratZOUARI, reactor does not stop on the thread termination. – falsetru Dec 26 '13 at 19:56