Python C程序子进程挂在“ for it in iter”

发布于 2021-02-02 23:19:25

好的,所以我试图从python脚本运行C程序。目前,我正在使用测试C程序:

#include <stdio.h>

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

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

#!usr/bin/python
import subprocess

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

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

为什么是这样?这正是我所看到的大多数示例作为其代码的内容,但是却没有读取该文件。

编辑:

有没有一种方法可以使它仅在需要读取内容时才能运行?

关注者
0
被浏览
305
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    这是一个块缓冲问题。

    以下是你对Python回答的案例版本的扩展:从subprocess.communicate()问题中读取流输入。

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

    stdio通常,如果基于程序的程序在终端中以交互方式运行,则将对这些程序进行行缓冲,并在将其stdout重定向到管道时对这些程序块进行缓冲。在后一种情况下,直到缓冲区溢出或刷新,你才会看到新行。

    为了避免fflush()在每次调用之后printf()调用,你可以通过在开始时在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
    

    还有其他实用程序,请参阅关闭管道中的缓冲。

    或使用伪TTY

    要欺骗子进程以使其认为是交互式运行,可以使用pexpect模块或其类似物,有关使用pexpect和pty模块的代码示例,请参见Python子进程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)
    

    pty通过使用pexpect

    pexpect将pty处理包装到更高级别的接口中:

    #!/usr/bin/env python
    import pexpect
    
    child = pexpect.spawn("/.main")
    for line in child:
        print line,
    child.close()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看