pygabriel
pygabriel

Reputation: 10008

twisted reactor stops too early

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?

Upvotes: 3

Views: 1172

Answers (1)

Rakis
Rakis

Reputation: 7874

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.callback which will, in turn, call reactor.stop(). There's no link between your program's logic and the call to reactor.stop(). Move the call into your program's core logic and you should be set. Specifically, I'd look at your CommandClient protocol's connectionMade() & dataReceived() methods as probable candidates for detecting your "im done" condition.

Upvotes: 5

Related Questions