I’m doing a batch script to connect to a tcp server and then exiting.
My problem is that I can’t stop the reactor, for example:
cmd = raw_input("Command: ")
# custom factory, the protocol just send a line
reactor.connectTCP(HOST,PORT, CommandClientFactory(cmd)
d = defer.Deferred()
d.addCallback(lambda x: reactor.stop())
reactor.callWhenRunning(d.callback,None)
reactor.run()
In this code the reactor stops before that the tcp connection is done and the cmd is passed.
How can I stop the reactor after that all the operation are finished?
The simple solution is to call
reactor.stop()at the point in your code when you detect your exit condition. Specifically, it would look like you’d want to call it somewhere within CommandClient after, I’m assuming, it sends your command to the remote machine and receives back the command’s exit code.As written, the reactor will start up and immediately execute
d.callbackwhich will, in turn, callreactor.stop(). There’s no link between your program’s logic and the call toreactor.stop(). Move the call into your program’s core logic and you should be set. Specifically, I’d look at your CommandClient protocol’sconnectionMade()&dataReceived()methods as probable candidates for detecting your “im done” condition.