9

他のページから情報を取得し、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
4

3 に答える 3

8

複数のリアクターを作成/実行しようとしているようです。すべてが同じリアクターに接続されます。DeferredLista を使用して、すべてのコールバックが終了するまで待機する方法を次に示します。

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()
于 2010-08-15T20:26:52.770 に答える
4

これを行うもう 1 つのクールな方法は、@defer.inlineCallbacks を使用することです。通常のシーケンシャル関数のように非同期コードを記述できます: http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.defer.html#inlineCallbacks

于 2012-12-19T02:14:42.603 に答える
2

まず、reactor.stop()をdeferedメソッドに入れてはいけません。これは、すべてを強制終了するためです。

現在、ツイストでは「待機」は許可されていません。コールバックの結果を出力するには、最初のコールバックの後に別のコールバックを追加するだけです。

于 2010-08-15T19:26:52.170 に答える