以交互方式在Python中运行外部可执行文件

2024-06-11 19:42:38 发布

您现在位置:Python中文网/ 问答频道 /正文

使用gcc test.c -o test.exe编译一个简单的C程序:

        /* TEST.C */
#include <stdio.h>
#include <string.h>
#define TRUE 1

int main (void)
{
  char p[256];
  strcpy(p, "start\0");
  printf("Welcome!\n");
  while (TRUE)
  {
    printf("Input: ");
    if (fgets(p, 255, stdin) == NULL)  break;
    if (p[0] == 'q')                   break;
    printf("You Entered: %s\n", p);
  }
  return 0;
}

Python中的subprocess模块通过端口启动程序并获取其stdin和{}。使用上述程序进行简单测试:

^{pr2}$

似乎在第一个通信命令上无限循环,用以下内容填充test.out

Welcome!
You Entered: bye
You Entered: bye
You Entered: bye
You Entered: bye
.
.
.

直到用户中断python进程。使用ris.stdin.write('bye\n')而不是communicate似乎根本不会发送输入,即使后面跟着ris.stdin.flush()。在

subprocess交互运行可执行文件的正确方法是什么?其目的是让程序的一个实例在后台运行,同时多个输入通过stdin传入,相应的输出从stdout或{}读取


Tags: test程序youtrueifincludestdingcc
1条回答
网友
1楼 · 发布于 2024-06-11 19:42:38

除了前面提到的C程序中的错误之外,您还多次调用.communicate().communicate()是一个一次性函数,它将其所有数据发送到子进程并等待子进程退出。在

如果必须使用.communicate(),请按如下方式使用:

com = ris.communicate(input='bye\nq\n')

或者,您可以使用ris.stdin.write(),如下所示:

^{pr2}$

相关问题 更多 >