sha*_*ait 25 python return generator tornado
我的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
Run Code Online (Sandbox Code Playgroud)
我知道
for line in response.body.split
Run Code Online (Sandbox Code Playgroud)
是一个发电机.但我会将值变量返回给调用该函数的处理程序.这可能吗?我能怎么做?
Mar*_*ers 38
您不能使用return值来退出Python 2或Python 3.0 - 3.2中的生成器.你需要使用yield加上return 没有表达式的a:
if response.error:
self.error("Error while retrieving the status")
self.finish()
yield error
return
Run Code Online (Sandbox Code Playgroud)
在循环本身中,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
Run Code Online (Sandbox Code Playgroud)
替代方案是提出异常或使用龙卷风回调.
在Python 3.3及更高版本中,return使用生成器函数中的值会导致值附加到StopIterator异常.对于async def异步生成器(Python 3.6及更高版本),return仍然必须是无值的.