我有一个程序,可以从其他页面中获取信息,并使用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
有帮助吗?

解决方案

似乎您正在尝试制作/运行多个反应堆。一切都依附在 相同的 反应堆。这是使用方法 DeferredList 等待所有回调完成。

另请注意 twisAmaz 返回值。该值通过 callbacks DeferredList 并出来 value. 。自从 DeferredList 保留所投入的内容的顺序,您可以将结果的索引与ISBN的索引交叉引用。

from twisted.internet import defer

def twisAmaz(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()

其他提示

另一种很酷的方法是 @defer.inlinecallbacks。它使您可以像常规顺序函数一样编写异步代码: http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.defer.html#inlinecallbacks

首先,您不应将反应器stop()放在递延方法中,因为它会杀死所有内容。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top