Python SyntaxError: (quot;#39;return#39; with argument inside generatorquot;,)(Python SyntaxError: (return with argument inside generator,))
问题描述
我的 Python 程序中有这个函数:
I have this function in my Python program:
@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("
"):
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
是一个生成器.但我会将 value 变量返回给调用该函数的处理程序.这可能吗?我该怎么办?
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?
推荐答案
在 Python 2 或 Python 3.0 - 3.2 中,您不能使用带有值的 return
来退出生成器.你需要使用 yield
加上一个 return
without 一个表达式:
You cannot use return
with a value to exit a generator in Python 2, or Python 3.0 - 3.2. You need to use yield
plus a return
without an expression:
if response.error:
self.error("Error while retrieving the status")
self.finish()
yield error
return
在循环本身中,再次使用 yield
:
In the loop itself, use yield
again:
for line in response.body.split("
"):
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.
在 Python 3.3 和更高版本中,生成器函数中带有值的 return
会导致将该值附加到 StopIterator
异常.对于 async def
异步生成器(Python 3.6 及更高版本),return
仍然必须是无值的.
In Python 3.3 and newer, return
with a value in a generator function results in the value being attached to the StopIterator
exception. For async def
asynchronous generators (Python 3.6 and up), return
must still be value-less.
这篇关于Python SyntaxError: ("'return' with argument inside generator",)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python SyntaxError: ("'return' with argument inside generator",)
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01