我的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
是一个生成器。但我会将值变量返回给调用该函数的处理程序。这可能吗?我该怎么办?
最佳答案
在 Python 2 或 Python 3.0 - 3.2 中,您不能使用带有值的 return
来退出生成器。您需要使用 yield
加上 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 及更高版本中,在生成器函数中返回一个值会导致该值附加到 StopIterator
异常。对于async def
异步生成器(Python 3.6及更高版本),return
仍然必须是无值的。
关于Python 语法错误 : ("' return' with argument inside generator", ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583353/