[英]How to send input to c++ through python
我已经使用以下代码将输入传递给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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.