如何停止在Python Grpc客户端的流中听
我正在在GRPC流上的Python线程中听:
responses = some_grpc_stub.FunctionThatReturnsStream()
for response in responses:
on_event(response)
我想执行此操作一段时间,然后 stop 听,因此 on_event
未调用同样,可能是在流完成之前。
我该怎么做?是否有正确的方法可以杀死该循环正在运行的线程?还是有某种方法可以使响应
过早结束,以便迭代结束并且线程可以运行到完成?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您可以考虑使用
cancel()
[1]?流呼叫返回一个既是未来和迭代器的对象,您可以调用wendess.cancel()
取消它。实际上,这需要在另一个线程中发生,因为迭代器块的消耗。如果您使用的是Asyncio API,则调用流呼叫将返回一个实现
asyncio.task
的对象,并支持cancel> CANCEL
[2]。您仍然可以使用wenders.cancel()
停止流。[1] https:// https://grpc.github.io/grpc/ python/grpc.html#grpc.rpccontext.cancel
[2] https://docs.python.org/3/library/asyncio-task.html#asyncio.task.cancel
maybe you can consider using
cancel()
[1]? The streaming call returns an object that is both a Future and an iterator, you can invokeresponses.cancel()
to cancel it. In practice, this needs to happen in another thread, because the consumption of the iterator blocks.If you are using AsyncIO API, the invoking a streaming call returns an object that implemented
asyncio.Task
, and supportscancel
[2]. You can still useresponses.cancel()
to stop a stream.[1] https://grpc.github.io/grpc/python/grpc.html#grpc.RpcContext.cancel
[2] https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel