首页 > 解决方案 > Python3:使用 infile 和 outfile 的 Popen 不会在 infile 的末尾停止

问题描述

为此,我尝试使用以下方法:

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()

这是我用于测试的 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 行。

标签: python-3.xsubprocess

解决方案


推荐阅读