gpt4 book ai didi

python - 使用管道将数据从 C 进程发送到 Python 进程

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:44 26 4
gpt4 key购买 nike

我正在尝试将数据从 C 程序发送到 python 程序(两者同时运行)。我正在尝试在 C 中使用 popen 函数。据我了解,无论我在 C 中写入文件描述符,都可以从 python 程序中的标准输入中读取。但是,python 程序似乎卡在它从 stdin 读取的位置。有什么建议吗?

这是 C 程序:

测试.c

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

int main(void) {

FILE * fp = popen("sudo python display.py", "w");
if (fp == NULL) {
printf("popen error\n");
exit(1);
}

int inc = 0;
char buf[10];

while(1) {
sprintf(buf, "%d", inc);
fputs(buf, fp);
inc++;
sleep(1);
}


return (0);
}

这里是python程序,应该读取“inc”的值并输出

显示.py

import sys

value = 0

while(True):
value = sys.stdin.read()
print value

程序似乎在 value = sys.stdin.read() 处挂起。我也尝试了 readline() 和 readlines(),结果相同。

最佳答案

readline() 如果您从 C 程序输出 lines 将起作用。

因为您从不打印换行符,readline 将永远等待。

没有参数的

read() 将等到 C 程序退出(或以其他方式关闭标准输出)。同样,您的程序永远不会发生这种情况

关于python - 使用管道将数据从 C 进程发送到 Python 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49143718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com