制作python程序,直到Twisted延迟返回值

问题描述 投票:9回答:3

我有一个程序可以从其他页面获取信息,并使用BeautifulSoup和Twisted的getPage解析它们。稍后在程序中,我将打印延迟过程创建的信息。目前,我的程序尝试在差异返回信息之前打印它。如何让它等待?

def twisAmaz(contents): #This parses the page (amazon api xml file)
    stonesoup = BeautifulStoneSoup(contents)
    if stonesoup.find("mediumimage") == None:
       imageurl.append("/images/notfound.png")
    else:
      imageurl.append(stonesoup.find("mediumimage").url.contents[0])

    usedPdata = stonesoup.find("lowestusedprice")
    newPdata = stonesoup.find("lowestnewprice")
    titledata = stonesoup.find("title")
    reviewdata = stonesoup.find("editorialreview")

    if stonesoup.find("asin") != None:
        asin.append(stonesoup.find("asin").contents[0])
    else:
        asin.append("None")
    reactor.stop()


deferred = dict()
for tmpISBN in isbn:  #Go through ISBN numbers and get Amazon API information for each
    deferred[(tmpISBN)] = getPage(fetchInfo(tmpISBN))
    deferred[(tmpISBN)].addCallback(twisAmaz)
    reactor.run()

.....print info on each ISBN
python twisted deferred
3个回答
8
投票

看来您正在尝试制造/运行多个反应堆。一切都附着在same反应堆上。这是使用DeferredList等待所有回调完成的方法。

还请注意,DeferredList返回一个值。该值通过twisAmaz callbacks传递并显示为DeferredList。由于value保留放入其中的内容的顺序,因此您可以将结果的索引与ISBN的索引进行交叉引用。

DeferredList

4
投票

另一种很酷的方法是使用@ defer.inlineCallbacks。它使您可以像常规顺序函数一样编写异步代码:from twisted.internet import defer def twisAmazon(contents): stonesoup = BeautifulStoneSoup(contents) ret = {} if stonesoup.find("mediumimage") is None: ret['imageurl'] = "/images/notfound.png" else: ret['imageurl'] = stonesoup.find("mediumimage").url.contents[0] ret['usedPdata'] = stonesoup.find("lowestusedprice") ret['newPdata'] = stonesoup.find("lowestnewprice") ret['titledata'] = stonesoup.find("title") ret['reviewdata'] = stonesoup.find("editorialreview") if stonesoup.find("asin") is not None: ret['asin'] = stonesoup.find("asin").contents[0] else: ret['asin'] = 'None' return ret callbacks = [] for tmpISBN in isbn: #Go through ISBN numbers and get Amazon API information for each callbacks.append(getPage(fetchInfo(tmpISBN)).addCallback(twisAmazon)) def printResult(result): for e, (success, value) in enumerate(result): print ('[%r]:' % isbn[e]), if success: print 'Success:', value else: print 'Failure:', value.getErrorMessage() callbacks = defer.DeferredList(callbacks) callbacks.addCallback(printResult) reactor.run()


2
投票

首先,您不应该在您的延迟方法中放入react..stop(),因为它会杀死所有内容。

现在,在Twisted中,不允许“等待”。要打印回调的结果,只需在第一个回调之后添加另一个回调。

© www.soinside.com 2019 - 2024. All rights reserved.