Python:与c+的通信+;使用<;时命令行程序不工作;cstdio>; 我有以下Python代码,它应该为C++程序提供初始输入,然后将其输出并反馈给它,直到程序完成执行: 普通的 我现在用两个简单的C++程序测试: 测试1.cpp: #包括 使用名称空间std; int main() { 对于(int i=0;i>n; cout
这是因为Python:与c+的通信+;使用<;时命令行程序不工作;cstdio>; 我有以下Python代码,它应该为C++程序提供初始输入,然后将其输出并反馈给它,直到程序完成执行: 普通的 我现在用两个简单的C++程序测试: 测试1.cpp: #包括 使用名称空间std; int main() { 对于(int i=0;i>n; cout,python,c++,subprocess,iostream,stdio,Python,C++,Subprocess,Iostream,Stdio,这是因为std::endl刷新ostream,而printf不刷新stdout, 正如您可以通过修改test__2.cpp看到的,如下所示: #include <cstdio> int main() { for( int i = 0; i < 3; ++i ) { int n; scanf("%d", &n); printf("%d\n", n+1); fflush(stdout); //
std::endl
刷新ostream
,而printf
不刷新stdout
,
正如您可以通过修改test__2.cpp
看到的,如下所示:
#include <cstdio>
int main()
{
for( int i = 0; i < 3; ++i )
{
int n;
scanf("%d", &n);
printf("%d\n", n+1);
fflush(stdout); //<-- add this
}
return 0;
}
这将解除所有标准流的缓冲。对于Windows,您将需要
研究如何做同样的事情。暂时我不知道。< /P>这是一个有效的解决方案,但不幸的是它不能解决我的问题,因为我需要用.c++来处理任何有效的C++程序。做同样的事?@black goat是的,我一直在思考这个问题,现在仍然是。请参阅更新。感谢您的输入。遗憾的是,我忘了提到我也需要它来在Windows上工作,但我将尝试找到与您的建议类似的方法。
#include <iostream>
using namespace std;
int main()
{
for( int i = 0; i < 3; ++i )
{
int n;
cin >> n;
cout << n+1 << endl;
}
return 0;
}
#include <cstdio>
int main()
{
for( int i = 0; i < 3; ++i )
{
int n;
scanf("%d", &n);
printf("%d\n", n+1);
}
return 0;
}
#include <cstdio>
int main()
{
for( int i = 0; i < 3; ++i )
{
int n;
scanf("%d", &n);
printf("%d\n", n+1);
fflush(stdout); //<-- add this
}
return 0;
}
import subprocess
cmd = ['/usr/bin/stdbuf', '-i0','-o0', '-e0', './test__2']
p = subprocess.Popen(cmd, 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)
x = p.stdout.readline()
print(x)
if p.poll() != None:
break