如何通过python将输入发送到c ++
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"
相关文章:
- C++如何通过用户输入删除列表元素
- 通过for循环使用用户输入填充列表
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 获取通过重定向传入的输入文件的名称?
- Arduino Nano:A4988 使用串行输入时通过定时器进行步进控制不稳定
- 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?
- 通过功能进行2D矢量输入和显示
- C++ 通过输入创建对象
- 如何通过 API 为 tflite 提供多维输入C++
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- 跳转到通过输入坐标定义的控制台屏幕位置
- TFLite 隔离错误,通过获取C++输入和输出
- C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?
- 如何通过一次运行将多个输入样本馈送到C++张量流模型
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- 如何通过输入十进制数打印UTF-8符号?
- 通过与输入进行比较来安排输出
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 为什么我的单行输入仅通过循环部分读取
- 我应该使用 DeviceContext 函数在管道中循环输入还是通过创建来输入