【发布时间】:2017-01-15 11:47:36
【问题描述】:
我有以下 python 代码,它应该为 C++ 程序提供初始输入,然后获取其输出并将其反馈给它,直到程序完成执行:
comm.py
p = subprocess.Popen('test__1.exe', bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False)
p.stdin.flush()
p.stdout.flush()
x = b'1\n'
while True:
p.stdin.write(x)
p.stdin.flush()
p.stdout.flush()
x = p.stdout.readline()
print(x)
if p.poll() != None:
break
我目前正在使用两个简单的 C++ 程序对其进行测试:
test__1.cpp:
#include <iostream>
using namespace std;
int main()
{
for( int i = 0; i < 3; ++i )
{
int n;
cin >> n;
cout << n+1 << endl;
}
return 0;
}
test__2.cpp
#include <cstdio>
int main()
{
for( int i = 0; i < 3; ++i )
{
int n;
scanf("%d", &n);
printf("%d\n", n+1);
}
return 0;
}
当 comm.py 打开 test__1.exe 时一切正常,但是当它打开 test__2.exe 时,它会在第一次调用时挂起readline()。 请注意,当我在执行前提供 test__2.exe 整个输入时不会出现此问题(即最初设置 x = '1\n2\n3\n') p>
什么可能导致这个问题?
(另外,comm.py 应该能够处理任何有效的 C++ 程序,因此仅使用 iostream 是不可接受的解决方案。)
编辑:我还需要在 Windows 上工作的解决方案。
【问题讨论】:
标签: python c++ subprocess iostream stdio