Pythonプログラムを作成する延期された延期が値を返すまで待ちます
質問
私は、他のページから情報を取得し、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
. 。 a以来 DeferredList
その中に入れられるものの順序を保持すると、結果のインデックスをISBNSのインデックスで相互参照できます。
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()
他のヒント
これを行うもう1つのクールな方法は、 @defer.inlinecallbacksを使用することです。通常のシーケンシャル関数のように非同期コードを書くことができます: http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.defer.html#inlinecallbacks
まず、すべてを殺すため、繰り返しの方法にreactor.stop()を置くべきではありません。
さて、ねじれた場合、「待機」は許可されていません。コールバックの結果を印刷するには、最初のコールバックの後に別のコールバックを追加するだけです。
所属していません StackOverflow