30

Python プログラムに次の関数があります。

@tornado.gen.engine
def check_status_changes(netid, sensid):        
    como_url = "".join(['http://131.114.52:44444/ztc?netid=', str(netid), '&sensid=', str(sensid), '&start=-5s&end=-1s'])

    http_client = AsyncHTTPClient()
    response = yield tornado.gen.Task(http_client.fetch, como_url)

    if response.error:
            self.error("Error while retrieving the status")
            self.finish()
            return error

    for line in response.body.split("\n"):
                if line != "": 
                    #net = int(line.split(" ")[1])
                    #sens = int(line.split(" ")[2])
                    #stype = int(line.split(" ")[3])
                    value = int(line.split(" ")[4])
                    print value
                    return value

そんなこと知ってる

for line in response.body.split

ジェネレーターです。しかし、関数を呼び出したハンドラに値変数を返します。これは可能ですか?どのようにできるのか?

4

1 に答える 1

45

returnPython 2 または Python 3.0 から 3.2 では、 with を使用してジェネレーターを終了することはできません。式なしyieldでplus aを使用する必要があります。return

if response.error:
    self.error("Error while retrieving the status")
    self.finish()
    yield error
    return

ループ自体で、yieldもう一度使用します。

for line in response.body.split("\n"):
    if line != "": 
        #net = int(line.split(" ")[1])
        #sens = int(line.split(" ")[2])
        #stype = int(line.split(" ")[3])
        value = int(line.split(" ")[4])
        print value
        yield value
        return

別の方法としては、例外を発生させるか、代わりに tornado コールバックを使用します。

Python 3.3 以降でreturnは、ジェネレーター関数に値を指定すると、その値がStopIterator例外にアタッチされます。async def非同期ジェネレーター (Python 3.6 以降) の場合、まだreturn値なしである必要があります。

于 2013-04-04T11:05:26.647 に答える