使用进程从 C++ 程序获取数据到 Python 程序

Using process to get data from C++ program to Python program

我正在尝试使用子进程将字符串从 C++ 程序连续发送到 Python 程序。

C++ 程序连续 运行s。

这是我的 C++ 程序:

#include <iostream>
#include <math.h>
#include <unistd.h>
int main(){
std::printf("This Sucks");
}

这是我的 Python 程序:

import os
import signal
from subprocess import Popen, PIPE, STDOUT
process = Popen('./Subprocess', stdin=PIPE,stdout=PIPE, universal_newlines = True, shell = True, preexec_fn = os.setsid)
while True:
        output = process.stdout.readline()
        if output == '' and process.poll is not None:
            break
        if output:
            print(output)

在上面显示的表格中,Python 程序将读入并打印一次“This Sucks”。但是,如果我将 C++ 程序中的 print 语句放在一个循环中,以便它重复打印,Python 程序将挂起并且不打印任何内容。

我需要 C++ 程序中的 print 语句在 while 循环中连续 运行,并且 Python 程序必须能够从 C++ 程序中读取,因为它 运行 无限期地不断地一遍又一遍地打印“这糟透了”。

最终目标是让 C++ 程序连续打印出传感器数据,并且 Python 程序能够读取这些数据。

我需要改变什么才能实现这一点?

python 程序期望一次读取一行。每行以换行符结束。

您的 C++ 程序无休止地打印相同的字符串,但没有尾随换行符。所以,对于 Python 程序来说,这看起来像是一个没有尽头的行,所以它会一直读取,读取它,直到它耗尽内存。

只需在字符串末尾添加一个换行符,“\n”。