python - 让 python 程序等到 Twisted deferred 返回一个值

标签 python twisted deferred

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

最佳答案

您似乎正在尝试制造/运行多个 react 器。所有东西都连接到同一个 react 堆。下面是如何使用 DeferredList等待所有回调完成。

另请注意,twisAmaz 会返回一个值。该值通过 callbacks DeferredList 传递并作为 value 输出。由于 DeferredList 保持放入其中的事物的顺序,您可以交叉引用结果的索引与 ISBN 的索引。

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

关于python - 让 python 程序等到 Twisted deferred 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3488854/

相关文章:

unit-testing - Angularjs 如何对依赖于另一个有 promise 的服务的服务进行单元测试?

python - 如何使用 pycrypto 执行河豚解密

python - 从 Twisted 中的 SSL 套接字读取

python - 广度优先搜索 : shortest reach hackerrank

python - 关闭 Twisted conch SSH 连接的正确方法是什么?

python - 使用 MySQL.connector 和 Twisted Python 执行多个查询

jquery - 使用 jQuery.Deferred 避免嵌套 setTimeout 回调

javascript - 对延迟图像应用淡入淡出效果

Python - 使用递归查找嵌套列表中的最大值和最小值之和

python - 字典 python 列表中特定键的值总和