Python C 程序子进程在 "for line in iter"处挂起

标签 python c subprocess freeze

好的,我正在尝试从 python 脚本运行 C 程序。目前我正在使用一个测试 C 程序:

#include <stdio.h>

int main() {
    while (1) {
        printf("2000\n");
        sleep(1);
    }
    return 0;
}

模拟我将使用的程序,该程序不断地从传感器获取读数。 然后我试图用python中的子进程从C程序中读取输出(在本例中为“2000”):

#!usr/bin/python
import subprocess

process = subprocess.Popen("./main", stdout=subprocess.PIPE)
while True:
    for line in iter(process.stdout.readline, ''):
            print line,

但这不起作用。从使用打印语句开始,它运行 .Popen 行,然后在 for line in iter(process.stdout.readline, ''): 处等待,直到我按下 Ctrl-C .

这是为什么?这正是我见过的大多数示例的代码,但它不读取文件。

有没有办法让它只在需要阅读的时候运行?

最佳答案

这是一个 block 缓冲问题。

以下内容是我对 Python: read streaming input from subprocess.communicate() 的回答的扩展版本。问题。

直接修复C程序中的stdout缓冲区

如果基于

stdio 的程序在终端中以交互方式运行,则它们通常会被行缓冲,并且当它们的 stdout 被重定向到管道时会被 block 缓冲。在后一种情况下,在缓冲区溢出或刷新之前,您不会看到新行。

为避免在每次 printf() 调用后调用 fflush(),您可以通过在开始时调用 C 程序来强制行缓冲输出:

setvbuf(stdout, (char *) NULL, _IOLBF, 0); /* make line buffered stdout */

在这种情况下,一旦打印了换行符,缓冲区就会被刷新。

或者在不修改C程序源码的情况下修复

stdbuf 实用程序可以让您在不修改源代码的情况下更改缓冲类型,例如:

from subprocess import Popen, PIPE

process = Popen(["stdbuf", "-oL", "./main"], stdout=PIPE, bufsize=1)
for line in iter(process.stdout.readline, b''):
    print line,
process.communicate() # close process' stream, wait for it to exit

还有其他可用的实用程序,请参阅 Turn off buffering in pipe .

或者使用伪TTY

为了让子进程认为它是交互式运行的,你可以使用 pexpect module或其类似物,有关使用 pexpectpty 模块的代码示例,请参阅 Python subprocess readlines() hangs .这是那里提供的 pty 示例的变体(它应该适用于 Linux):

#!/usr/bin/env python
import os
import pty
import sys
from select import select
from subprocess import Popen, STDOUT

master_fd, slave_fd = pty.openpty()  # provide tty to enable line buffering
process = Popen("./main", stdin=slave_fd, stdout=slave_fd, stderr=STDOUT,
                bufsize=0, close_fds=True)
timeout = .1 # ugly but otherwise `select` blocks on process' exit
# code is similar to _copy() from pty.py
with os.fdopen(master_fd, 'r+b', 0) as master:
    input_fds = [master, sys.stdin]
    while True:
        fds = select(input_fds, [], [], timeout)[0]
        if master in fds: # subprocess' output is ready
            data = os.read(master_fd, 512) # <-- doesn't block, may return less
            if not data: # EOF
                input_fds.remove(master)
            else:
                os.write(sys.stdout.fileno(), data) # copy to our stdout
        if sys.stdin in fds: # got user input
            data = os.read(sys.stdin.fileno(), 512)
            if not data:
                input_fds.remove(sys.stdin)
            else:
                master.write(data) # copy it to subprocess' stdin
        if not fds: # timeout in select()
            if process.poll() is not None: # subprocess ended
                # and no output is buffered <-- timeout + dead subprocess
                assert not select([master], [], [], 0)[0] # race is possible
                os.close(slave_fd) # subproces don't need it anymore
                break
rc = process.wait()
print("subprocess exited with status %d" % rc)

或者通过pexpect

使用pty

pexpectpty 处理包装到 higher level interface 中:

#!/usr/bin/env python
import pexpect

child = pexpect.spawn("/.main")
for line in child:
    print line,
child.close()

Q: Why not just use a pipe (popen())?解释了为什么伪 TTY 很有用。

关于Python C 程序子进程在 "for line in iter"处挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503671/

相关文章:

python - celery 重复任务不执行

c++ - 为什么在 C 中减去 '0' 会得到 char 代表的数字?

c - C 中的宏与预定义数据类型在存储方面有何不同?

python - 如何使用 subprocess.check_call 一次性运行多个命令

python - 从 Python 的子进程调用 scp 不适用于文件列表\{a,b,c\}

python - 不确定为什么 "yield from"不处理 StopIteration

python - 在 tkinter 窗口上使用网格管理器时如何实现滚动条

python - 如何使用 "condense"长递归 Polars 表达式?

c++ - 寻找单图像 HDR 算法

python - 计时子流程完成需要多长时间