如何停止在Python Grpc客户端的流中听

发布于 2025-01-28 06:36:04 字数 322 浏览 2 评论 0 原文

我正在在GRPC流上的Python线程中听:

responses = some_grpc_stub.FunctionThatReturnsStream()
for response in responses:
  on_event(response)

我想执行此操作一段时间,然后 stop 听,因此 on_event 未调用同样,可能是在流完成之前。

我该怎么做?是否有正确的方法可以杀死该循环正在运行的线程?还是有某种方法可以使响应过早结束,以便迭代结束并且线程可以运行到完成?

I am listening in a python thread on a gRPC stream that never ends:

responses = some_grpc_stub.FunctionThatReturnsStream()
for response in responses:
  on_event(response)

I want to do this for a while, and then stop listening, so that on_event isn't called again, possibly before the stream is done.

How do I do that? Is there a correct way to just kill the thread in which this loop is running? Or is there some way to have responses end prematurely so iteration ends and the thread can run to completion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗳卜坏 2025-02-04 06:36:04

也许您可以考虑使用 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 invoke responses.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 supports cancel [2]. You can still use responses.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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文