[Twisted-Python] another probably very simple question

Andrew Bennetts andrew-twisted at puzzling.org
Mon Nov 17 20:01:23 EST 2003


On Mon, Nov 17, 2003 at 05:34:24PM -0500, Phil Christensen wrote:
> 
> i want to be able to continually prompt the user for a string that gets
> sent to a "parse" method on the remote object. i'm not exactly sure the
> right way to do this. do I just add a callback to the deferred returned by
> call remote?
> 
> here's my code so far:
> 
> def main():
>     config = Options()
>     if(config['login'] == None):
>         config['login'] = getpass.getuser()
>     passwd = getpass.getpass("%s@%s's password: " % (config['login'],
>                                                      config['host']))
> 
>     client = TextClient()
>     factory = pb.PBClientFactory()
>     reactor.connectTCP(config['host'], int(config['port']), factory)
>     defer = factory.login(credentials.UsernamePassword(config['login'],
>                                                        passwd), client)
>     defer.addCallback(connected)
>     reactor.run()
> 
> def connected(perspective):
>     command = raw_input("> ");
>     defer = perspective.callRemote("parse", command)
>     defer.addCallback(connected)

Calling raw_input is a bad idea.  It will block.

You should either use twisted.internet.stdio (which is probably more work
than you care to do -- but see doc/examples/cursesclient.py for an example
that uses stdio and curses to make a simple irc client), or run raw_input in
a thread:


from twisted.internet import threads

def connected(perspective):
    deferred = threads.deferToThread(raw_input, "> ")
    deferred.addCallback(lambda cmd: perspective.callRemote("parse", cmd))
    deferred.addCallback(lambda res: connected(perspective))


Note that perspective.callRemote will return a Deferred -- but that's ok,
the Deferreds automatically cope with (i.e. wait for) deferred results from
callbacks :)

Something else to notice is that Deferreds pass the result of the previous
callback (or the original result, for the first callback) to each callback,
which is why I wrote:
    deferred.addCallback(lambda res: connected(perspective))
rather than your:
    defer.addCallback(connected)

-Andrew.





More information about the Twisted-Python mailing list