Python SyntaxError: ("'return' with argument inside generator",)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15809296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:04:24  来源:igfitidea点击:

Python SyntaxError: ("'return' with argument inside generator",)

pythonreturngeneratortornado

提问by sharkbait

I have this function in my Python program:

我的 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

I know that

我知道

for line in response.body.split

is a generator. But I would return the value variable to the handler that called the function. It's this possible? How can I do?

是一个发电机。但是我会将 value 变量返回给调用该函数的处理程序。这可能吗?我能怎么做?

采纳答案by Martijn Pieters

You cannot use returnwith a value to exit a generator in Python 2, or Python 3.0 - 3.2. You need to use yieldplus a returnwithoutan expression:

return在 Python 2 或 Python 3.0 - 3.2 中,您不能使用带值退出生成器。您需要使用带表达式的yieldplus :return

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

In the loop itself, use yieldagain:

在循环本身中,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

Alternatives are to raise an exception or to use tornado callbacks instead.

替代方法是引发异常或使用龙卷风回调。

In Python 3.3 and newer, returnwith a value in a generator function results in the value being attached to the StopIteratorexception. For async defasynchronous generators (Python 3.6 and up), returnmust still be value-less.

在 Python 3.3 和更新版本中,return生成器函数中的值会导致该值附加到StopIterator异常。对于async def异步生成器(Python 3.6 及更高版本),return必须仍然是无值的。