这是来自“Twisted Network Programming Essential”的一个例子:
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
import sys
from random import random
class ResourcePrinter(Protocol):
def __init__(self, finished):
self.finished = finished
def dataReceived(self, data):
print data
def connectionLost(self, reason):
self.finished.callback(None)
def printResource(response):
# Nothing added to this 'finished'
finished = Deferred()
response.deliverBody(ResourcePrinter(finished))
return finished
def printError(failure):
print >>sys.stderr, failure
def stop(result):
reactor.stop()
if len(sys.argv) != 2:
print >>sys.stderr, 'Usage'
exit(1)
agent = Agent(reactor)
d = agent.request('GET', sys.argv[1])
d.addCallbacks(printResource, printError)
d.addBoth(stop)
reactor.run()
但既然它从来不呼入addCallback()
,finished
那printResource()
为什么stop()
最后会被呼入connectionLost()
呢?