python-3.x - Python3:使用 infile 和 outfile 的 Popen 不会在 infile 的末尾停止
问题描述
- 我想调用一个交互式命令行程序(使用 cin/cout 的 c++)。
- 我想通过输入文件定义输入。
- 我希望将输出写入输出文件。
- 在使用输入文件中的所有输入之后,应该终止执行的程序,即使它会自然运行。
- 目标机器是windows 10。
为此,我尝试使用以下方法:
from subprocess import *
with open("input.txt", "r") as ifile:
with open("output.txt","w") as ofile:
p = Popen(["./example.exe"], stdin=ifile, stdout=ofile, stderr=None, universal_newlines=True )
p.wait()
- 我也用 call 而不是 Popen 尝试过,但结果相同。
- 我也尝试过 p.stdin.write/readline,但我想出的所有东西都会挂起(例如,因为 exe 程序在 cin 内等待)或混合了订单。
这是我用于测试的 cpp 代码:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string inputString("");
for (int i = 0; i< 200; ++i){
cout << "type a number: " << endl;
cin >> inputString;
if(inputString == "1"){
cout << "eins" << endl;
} else if (inputString == "2"){
cout << "zwei" << endl;
} else if (inputString == "blub"){
break;
}
else{
cout << "unknown" << endl;
}
}
return 0;
}
在使用输入文件中的所有输入行之后,我希望 python 代码停止运行。相反,最后一行被重复用作输入(任意*次)或程序在中间终止。
*任意:Outfile 总是正好有 400 行。