[Twisted-Python] follow up: at what point does reactor.run() need to be called?

Michal Pasternak michal at pasternak.w.lub.pl
Wed Apr 7 02:35:43 MDT 2004


Damon Fasching [Wed, Apr 07, 2004 at 01:04:34AM -0700]:
> I'm still confused.

Perhaps this will help you:

	from twisted.internet import reactor
	
	print "Press CTRL+C to see second message"
	reactor.run()
	print "Second message, program exiting"

> hang.  (server does not get the shutdown call and
> client is not stopped, so it seems the callback for
> getRootObject is not executed.)

How do you want to execute shutdown call if there are *no* functions calling
it? (because you add Callback _after_ the reactor loop has finished)?

> > It doesn't hang, it just gets the root object, but 
> > has no callback to pass it to.
> 
> Huh?  What about the line
> d.addCallback(gotRootObject)?  It's still there, just
> a little further down

Yes, after reactor.run() . Which basically sounds similar to "Hey, I call
that function, only after sys.exit(), why doesn't it run?"

> What I really see as a limitation is that it seems
> that I must connect to all of my servers before
> starting the reactor

I already gave you example how to start connecting servers _after_ you do
reactor.run() (use reactor.callLater)

I really don't understand what's your problem, perhaps re-read my responses
until sudden enlightement comes :)

> For example, why does the client hang if I change the
> last lines to the following?

> What have I misunderstood?
> 
> How can I connect to a server on the fly?

	from twisted.internet import reactor
	
	def failureSoQuitApp():
		print "failure"
		reactor.stop()
		
	def serverOneGotRootObjectAndShutdownReactor(*args):
		print "Got some args! %s" % args
		print "Quitting the app"
		reactor.stop()
	
	def connectServerOne():
		# do something
		factory = pb.PBClientFactory()
		reactor.connectTCP("localhost", 8080, factory)
		factory.getRootObject().addCallbacks(serverOneGotRootObjectAndShutdownReactor,
						     failureSoQuitApp)

	def connectServerTwo():
		# copy above stuff
		
	def connectServersAfterReactorHasBeenRun():
		connectServerOne()
		connectServerTwo()
		
	reactor.callLater(0, connectServersAfterReactorHasBeenRun)
	reactor.run()
	
You *must* run the reactor in order to collect deferred results.

-- 
mp




More information about the Twisted-Python mailing list