0

I have a C++ program that I want to run continuously that gathers sensor data on a Raspberry Pi. I'm trying to use Python's subprocess feature to launch the C++ program, and then occasionally read output from the C++ program. However, I am having trouble reading in data from the C++ program to Python. The Python program always returns nothing. What am I doing wrong? Is there a more reliable way to read in data to a Python program from a continously running C++ program?

Here's the C++ program:

#include <stdio.h>
#include <signal.h>
#include <pigpio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <math.h>
#include <iostream>

int main(int argc, char *argv[])
{
  std::cout<< "Test of disturbance input\n";
  // Calculations are performed once every 0.25 seconds.
  time_sleep(0.25);
}

And here's the Python program

import os
import signal
from subprocess import Popen, PIPE, STDOUT

process = Popen('./testSubprocess', stdin=PIPE,stdout = PIPE)

while True:
    output = process.stdout.readline()
    print(output)
  • This may be a duplicate question. Please see: https://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running, which further leads to: https://stackoverflow.com/a/17698359/4279 – Arnab De Apr 26 '21 at 16:43
  • Your C++ program prints one thing and then exits. Your Python code launches that program once and then repeatedly tries to read from it. Those things don't match. – Ulrich Eckhardt Apr 26 '21 at 17:17

1 Answers1

0

In addition to my comment above, both of the following seems to work:

while True:
    completed = subprocess.run(['./testSubprocess'], stdout=subprocess.PIPE)
    print(completed.stdout.decode())

and

while True:
    with subprocess.Popen(["./testSubprocess"], stdout=subprocess.PIPE, bufsize=1,
            universal_newlines=True) as p:
        for line in p.stdout:
            print(line)
Arnab De
  • 402
  • 4
  • 12