views:

162

answers:

1

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?

+4  A: 

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.

Rakis
I think you mean "connectionMade" and "dataReceived", not "on_connect" and "on_data_received".Also, this is a cool helper for this use-case (it extends the main point of your answer, doesn't replace it):http://divmod.org/trac/browser/trunk/Epsilon/epsilon/react.py
Jean-Paul Calderone
Yeah, you caught me JP. I couldn't recall the exact method names off hand and was too lazy to read online docs ;-)
Rakis
@Rakis, do edit your answer to include what JP just mentioned. I'm sure that'll help the scores of people who havent yet read your fine answer.
jeffjose
@jeffjose Done. I can't believe I didn't think of that myself. Thanks jeffjose.
Rakis