对属于进程输出的每一行执行某些操作

发布于 2024-09-30 14:00:07 字数 122 浏览 0 评论 0原文

使用 subprocess 模块时,如何对进程输出的每一行执行某些操作?我不想等待所有输出,就像使用 communicate 时一样,而是在生成后立即对其进行处理。这可以做到吗?

When using the subprocess module, how can I do something with each line of a process's output? I don't want to wait for all the output, like when using communicate, but rather do something with it as soon as it's produced. Can this be done?

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

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

发布评论

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

评论(1

仅一夜美梦 2024-10-07 14:00:07

不幸的是,将其添加到子进程的提议尚未被接受: http://www.python .org/dev/peps/pep-3145/

以下是使用现有子进程执行此操作的方法:http://code.activestate.com/recipes/440554/

评论者还指出了这个简单的解决方案(有一些缺点):

flags = fcntl.fcntl(subprocess.stdout, fcntl.F_GETFL)
fcntl.fcntl(subprocess.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)

Unfortunately the proposal to add this to subprocess is not yet accepted: http://www.python.org/dev/peps/pep-3145/

Here is a recipe for doing it with the existing subprocess: http://code.activestate.com/recipes/440554/

A commenter also notes this simple solution (with some downsides):

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