如何通过python将输入发送到c ++

How to send input to c++ through python

本文关键字:输入 何通过 python      更新时间:2023-10-16

我使用以下代码将输入传递给 cpp 程序,该程序读取输入并打印它。

from subprocess import Popen, PIPE
p = Popen(['a.exe'], shell=True, stdout=PIPE, stdin=PIPE)
for ii in range(10):
value = str(ii) + 'n'
value = bytes(value, 'UTF-8')  # Needed in Python 3.
p.stdin.write(value)
#p.stdin.flush()
result = p.stdout.readline().strip()
print(result)

以下是 python 的输出

b''
b''
b''
b''
b''
b''
b''
b''
b''
b''

编辑: 以下是 cpp 文件的代码

#include<iostream>
using namespace std;
int main()
{
int a[10];
for(int i=0;i<10;i++)
{
cin>>a[i];
cout<<a[i];
std::cout.flush();
}
return 0;
}

我在 Linux 上尝试过代码,但遇到了两个问题

  • 在 Python 中,我必须使用完整路径来a.exe运行它

  • 在 CPP 中,我不得不添加<< 'n'因为它在没有n的情况下发送文本,并且p.stdout.readline()正在等待n

没有完整的路径,我看到了很多b''(第一行有消息"... not found")

没有<< 'n'剧本冻结,因为readline()在等待n

编辑:我

忘记了我不得不添加p.stdin.flush().


编辑:正如@Sugar评论中建议的那样 - 使用std::endl而不是"n"