Python 子进程是否产生输出

发布于 2024-10-02 10:20:40 字数 354 浏览 0 评论 0原文

这个问题与:

python,子进程:从子进程读取输出

如果P 是一个以命令启动的子进程,

import subprocess

P = subprocess.Popen ("command", stdout=subprocess.PIPE)

我们可以通过 P.stdout.readline () 读取 P 产生的输出。但这是一个阻塞读取。如何检查是否有输出可供读取(无阻塞)?

This question is in relation to:

python, subprocess: reading output from subprocess

If P is a subprocess started with a command along the lines of

import subprocess

P = subprocess.Popen ("command", stdout=subprocess.PIPE)

we can read the output P produces by P.stdout.readline (). This is a blocking read though. How can I check if there is output ready for reading (without blocking)?

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

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

发布评论

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

评论(1

带上头具痛哭 2024-10-09 10:20:40

如果您使用的是 *nix,那么您可以使用 select 模块来轮询 stdout 文件描述符

import subprocess
import select
poller = select.epoll()

P = subprocess.Popen ("command", stdout=subprocess.PIPE)
poller.register(P.stdout, select.EPOLLHUP)

while True:
    #block indefinitely: timeout = -1
    #return immediately: timeout = 0
    for fd, flags in poller.poll(timeout=0)
        foo = P.stdout.readline()
    #do something else before the next poll

If you are using *nix, then you can use the select module to poll the stdout file descriptor

import subprocess
import select
poller = select.epoll()

P = subprocess.Popen ("command", stdout=subprocess.PIPE)
poller.register(P.stdout, select.EPOLLHUP)

while True:
    #block indefinitely: timeout = -1
    #return immediately: timeout = 0
    for fd, flags in poller.poll(timeout=0)
        foo = P.stdout.readline()
    #do something else before the next poll
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文