将数据从 c++ 文件连续发送到 Python 脚本以进行进一步处理

Send data continuously from a c++ file to a Python script for further processing

本文关键字:脚本 Python 处理 进一步 数据 c++ 文件 连续      更新时间:2023-10-16

我想持续接收程序的stdout和stderr(可选(。以下是该程序的标准输出:

got 3847 / 0 / 0 / 0 pkts/drops/pktinfisue/crpts with 40.6859 Mbps during 8.166 sec
timestamp: 3412618016 0 
got 3842885 / 0 / 0 / 0 pkts/drops/pktinfisue/crpts with 40.6424 Gbps during 1.00052 sec
timestamp: 3412700516 55
got 4190413 / 0 / 0 / 0 pkts/drops/pktinfisue/crpts with 44.3178 Gbps during 1.00041 sec
timestamp: 3412792016 116

到目前为止使用管道:

#include <iostream>
#include <string>
#include <unistd.h>
#include <stdexcept>
#include <python3.7m/Python.h>
using namespace std;
string exec(const char* cmd) {
char buffer[40];
string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
c++;
result += buffer;
cout<<buffer<<endl;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
int main()
{
char *dirr;
dirr = "/home/user/receiver";
int chdir_return_value;
chdir_return_value = chdir(dirr);
exec("sudo ./rx_hello_world");
return 0;
}

我想我能够在不同的行中获取数据,如下所示:

got 3847 / 0 / 0 / 0 pkts/drops/p
ktinfisue/crpts with 40.6859 Gbps durin
g 8.166 sec
timestamp: 3412618016 0

现在我想将这些数据发送到 Python 脚本,以便我可以解析和分析数据。 例如,我想在每 10 秒左右获得40.6859 Mbps的平均值。

有关将这些数据发送到python以便我可以轻松解析这些数字的任何帮助都将是一个很大的帮助。

你正在寻找python中子进程模块的Popen类。

相当于C函数的Python可以沿着以下行:

from subprocess import Popen, PIPE

def exec(*args):
with Popen(args, stdout=PIPE) as proc:
while proc.poll() is None:
print(proc.stdout.read(40))
print(proc.stdout.read())

作为替代解决方案,您还可以将 C 代码包装在 python 中并从 python 调用 C API。网上有几个关于如何做到这一点的资源。