2010-08-15 95 views
8

我有一个程序,从其他页面获取信息并使用BeautifulSoup和Twisted的getPage解析它们。稍后在程序中打印延迟进程创建的信息。目前我的程序试图在不同的返回信息之前打印它。我怎样才能让它等待?使python程序等待,直到扭曲延迟返回值

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 
+0

你真的使用1空格缩进... – 2010-08-15 19:30:31

+0

这是一个格式问题在这里,实际的代码使用标签 – 2010-08-15 22:24:32

回答

8

看起来你正在试图制造/运行多个反应堆。一切都被附加到同样的反应堆。以下是如何使用DeferredList等待所有回调完成。

另请注意,twisAmaz会返回一个值。该值通过callbacksDeferredList并且作为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() 
+0

看起来不错,谢谢Aaron! – 2010-08-15 20:36:41

2

首先,你不应该在你的延期方法中放一个reactor.stop(),因为它会杀死所有的东西。

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

+0

谢谢,吕克!我可以问一下reactor.stop()应该在哪里? – 2010-08-15 19:39:18

+0

当我说没有放置一个reactor.stop()时,我的意思是不把它放在第一个延期代码中,因为它会阻止一切。 所以你应该把它放在最后延迟(打印结果的那个),你确定你想停止你的程序。 请注意:您应该使用addCallbacks(method1,error_method)来捕捉潜在的错误。 – 2010-08-15 20:02:59

+0

查看http://twistedmatrix.com/documents/current/core/howto/deferredindepth.html上关于推迟的教程,特别是名为“回调可以返回延迟”的部分。 – 2010-08-15 20:09:03