Read output from C in Python simultaneously as it's being printed

Viewed 44

I have a simple C program that prints numbers 1 to 10 every 5 seconds. I want to have a Python script that reads and prints these numbers as they're being printed in C. I have these two files here, but right now test.c prints everything from 1-10 at once. How can I have them printed from test.py as they're being printed in test.c?

test.py:

#!/usr/bin/env python3

from subprocess import Popen, PIPE, CalledProcessError

cmd = "./test"

print("Running..")
with Popen(cmd, shell=True, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='') # process line here

if p.returncode != 0:
    raise CalledProcessError(p.returncode, p.args)

And here is test.c:

#include<stdio.h>
#include <unistd.h>

int main(){
 
    int i;
    
    //Print numbers from 1 to 10
    for(i = 1; i <= 10; i++){
      sleep(5);
      printf("%d ",i);
    }
    return 0;
}

I've been compiling test.c like:

gcc test.c -o test

How can I make the C file print numbers one by one? How can I simultaneously read output from C files as they're being printed?

1 Answers

Based on @Shawn's comment, adding fflush(stdout) flushes the output stream the solves the problem. Also adding a newline printf("%d \n",i); makes the c program print numbers every 5 seconds.

Related