在 Ubuntu 中将数据从 C 馈送到 Python

Feeding data from C to Python in Ubuntu

我试图在 C 中生成数字,然后将它们传递到 python,并使用 sys.stdin 打印数据。 C中生成数字的代码是这样的,

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>

int main() {
        unsigned int i;

        srand(time(NULL));

        while (1) {
                i = random() % 15000;
                printf("%u.%03u", i / 1000, i % 1000);
                printf("\n");
                usleep(100 * 1000);
        }
}

在python中读取和打印的程序是这样的:

import sys

while(1):
    for line in sys.stdin:
        print(line[:-1])

然后,在编译 c 文件 gcc gen.c 之后,我将其通过管道传输到 python ~/a.out | python3 new.py。但是,这仅在我删除 C 代码中的 usleep 部分时才有效。当我删除 usleep 位时,它工作正常,但是对于 usleep 部分,它不打印任何东西,它似乎卡在 new.py.

的第 4 行

您只需刷新输出即可。 Why does stdout need explicit flushing when redirected to file? 中解释了原因,即管道改变了缓冲行为。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
//#include <Windows.h>

int main() {
        unsigned int i;

        srand(time(NULL));

        while (1) {
                i = random() % 15000;
                printf("%u.%03u", i / 1000, i % 1000);
                printf("\n");
                fflush(stdout);
                usleep(1000 * 1000);

        }
}
$ gcc gen.c -o gen       
$ ./gen  | python3 new.py
14.383
0.886