Python C program subprocess hangs at "for line in iter"

Viewed 7364

Ok so I'm trying to run a C program from a python script. Currently I'm using a test C program:

#include <stdio.h>

int main() {
    while (1) {
        printf("2000\n");
        sleep(1);
    }
    return 0;
}

To simulate the program that I will be using, which takes readings from a sensor constantly. Then I'm trying to read the output (in this case "2000") from the C program with subprocess in python:

#!usr/bin/python
import subprocess

process = subprocess.Popen("./main", stdout=subprocess.PIPE)
while True:
    for line in iter(process.stdout.readline, ''):
            print line,

but this is not working. From using print statements, it runs the .Popen line then waits at for line in iter(process.stdout.readline, ''):, until I press Ctrl-C.

Why is this? This is exactly what most examples that I've seen have as their code, and yet it does not read the file.

Is there a way of making it run only when there is something to be read?

3 Answers
Related