python - 在 Python 中交互运行外部可执行文件

标签 python c subprocess

使用 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 模块预示着启动一个程序并获取它的 stdinstdout 。使用上述程序进行简单测试:

import subprocess
from subprocess import PIPE, STDOUT

output = open("test.out","w")
ris = subprocess.Popen(executable="test.exe", args="", stdin=PIPE,
                       stdout=output, stderr=STDOUT,
                       universal_newlines=True, shell=True)  
com = ris.communicate(input='bye\n')
com = ris.communicate(input='q\n')
output.close()

似乎在第一个通信命令上无限循环,填充 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 读取相应的输出或stderr

最佳答案

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

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

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

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

import subprocess
from subprocess import PIPE, STDOUT

output = open("test.out","w")
ris = subprocess.Popen(executable="/tmp/test.exe", args="", stdin=PIPE,
                       stdout=output, stderr=STDOUT,
                       universal_newlines=True, shell=True)
com = ris.stdin.write('bye\n')
com = ris.stdin.write('q\n')
ris.stdin.flush()
output.close()
ris.wait()

关于python - 在 Python 中交互运行外部可执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36049149/

相关文章:

python - 使用 Google App Engine (Python) 的 PDF 缩略图

python - 您如何从在 blender 外部运行的 python 脚本在 blender 中编写命令?

c - C 语言中的 UTM 到 WGS84

python - 无法使用 popen 启动两个交互式 shell

python - 使用 shell=True w/list 时忽略 subprocess.call() 参数

python - 可以通过自定义 SQLObject Select 调用获取生成器吗?

python - 我可以将 Python 的 CSV 阅读器与 Google Fusion Tables 结合使用吗?

c - 如何打印一组输入整数中最小的数字?

c - 从 'atoi' 收到未经验证的整数值

python - 可执行文件失败时从subprocess.Popen()捕获错误