Thanks for that advice - as you suggested I'm now passing a Deferred down into the SSHConnection to receive a reference to the connection object, which works really well.
I now have a follow-on question. This is my situation: I'd like to set up an SSHConnection and associate it with a Machine object at program startup, then execute arbitrary commands over this SSHConnection at run-time.
The problem I'm facing is that after instantiating the Twisted objects, calling reactor.run() doesn't return, so I can't create a standalone SSHConnection and attach it as a utility to a Machine object.
class Machine(object):
def __init__(self, address):
self.conn = MachineConnection(self, address, 'user')
class MachineConnection(object):
def __init__(self, address, user):
self.address = address
self.port = 22
self.user = user
d=defer.Deferred()
d.addCallback(self.__conn_ready)
d.addErrback(self.__conn_err)
factory = protocol.ClientFactory(self.user, d) # I'm actually using a subclass
reactor.connectTCP(self.address, self.port, factory)
reactor.run()
Here, I've left out definitions of my conch subclasses, and methods on Machine and MachineConnection, but I don't think they're relevant.
The issue is that reactor.run() in the last line of MachineConnection.__init__ starts Twisted up, creates the connection and so on, but doesn't return control to the original flow of code. I've tried starting separate threads for the connections, but Twisted seems to rely on running in the main thread.
Are the any suggestions on how to set up backgrounded Twisted connections that can be interacted with as daemonic threads?
Thank you,
James