【发布时间】:2018-08-10 19:47:25
【问题描述】:
我有一个无法修改的程序。该程序将数据打印到stdout而不刷新它或将\n放入其中并等待输入等等。
我的问题是如何从 Python 脚本实时打印stdout 并写入他的stdin?我找到了一些方法可以在不关闭程序的情况下写入他的stdin,但打印他的stdout 的问题仍然存在。
事实上,线程存在一些问题,Popen 和 fcntl 实时打印他的输出,但他们都假设程序在每次打印后刷新 stdout 并在其输出中包含 \n。
为了清楚起见,假设我有一个程序test.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char name[100], age[100], location[100];
fprintf (stdout, "\nWhat is your name : ");
fgets (name, sizeof (name), stdin);
name[strcspn (name, "\n")] = '\0';
fprintf (stdout, "How old are you : ");
fgets (age, sizeof (age), stdin);
age[strcspn (age, "\n")] = '\0';
fprintf (stdout, "Where do you live : ");
fgets (location, sizeof (location), stdin);
location[strcspn (location, "\n")] = '\0';
fprintf (stdout, "\nHello %s, you have %s years old and live in
%s\n\n", name, age, location);
return 0;
}
我怎样才能从 Python 脚本中输出第一个 fprintf() 然后将答案写入他的标准输入等等,就像我可以简单地启动 test.c 一样?
目的是控制从脚本发送到该程序的数据,并且仍然可以返回所发生的事情。
【问题讨论】:
-
这进入了不可移植的坏境(至少可能如此)。您需要在哪些操作系统上运行您的代码。
-
对不起,这是针对 Linux 的
标签: python subprocess stdout stdin nonblocking