Reputation: 63
I want to continuously receive stdout and stderr(optional) of a program. The following is the stdout of the program:
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
So far using pipes:
#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;
}
i think i am able to get the data in different lines like this:
got 3847 / 0 / 0 / 0 pkts/drops/p
ktinfisue/crpts with 40.6859 Gbps durin
g 8.166 sec
timestamp: 3412618016 0
Now i want to send these data to a Python script so that i can parse and analyze the data. for example, i want to get the average of the 40.6859 Mbps say after every 10 seconds or so.
Any help regarding sending these data to python so that i can parse these numbers easily will be a great help.
Upvotes: 0
Views: 527
Reputation: 751
You are looking for Popen class of the subprocess module in python.
Python equivalent of the C function could be along the lines of
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())
As an alternative solution, you could also wrap the C code in python and call the C API from python. There are several resources online on how to do that.
Upvotes: 1