【发布时间】:2014-07-31 22:55:29
【问题描述】:
我必须使用标准输出和标准输入将数组从 Python 传递到 C++ 并返回。我可以将它传递给 C++ 。但是我不能将它发送回python。我想我不明白如何设置标准输出模式。请给我建议。谢谢你。 我的 Python 代码:
import struct
import subprocess
#import msvcrt
#import os
import random
array = [1.0 for _ in range(10)]
proc = subprocess.Popen(['test.exe'], stdin=subprocess.PIPE, stdout = subprocess.PIPE)
for item in array:
proc.communicate(struct.pack('<f', item))
data = bytes()
while len(data) < len(array)*4:
data = data + proc.communicate()[0]
print (len(data))
#print('Python:')
#msvcrt.setmode (proc.stdout.fileno(), os.O_BINARY)
proc.stdin.close()
proc.stdout.close()
proc.wait()
我的 C++ 代码:
#include "stdafx.h"
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
int main(void)
{
int result;
// Set "stdin" to have binary mode:
result = _setmode(_fileno(stdin), _O_BINARY);
if (result == -1)
perror("Cannot set mode");
else
fprintf(stderr, "'stdin' successfully changed to binary mode\n");
// Set "stdout" to have binary mode:
result = _setmode(_fileno(stdout), _O_BINARY);
if (result == -1)
perror("Cannot set mode");
else
fprintf(stderr, "'stdout' successfully changed to binary mode\n");
int i = 0;
while (!std::cin.eof())
{
float value;
std::cin.read(reinterpret_cast<char*>(&value), sizeof(value));
if (std::cin.gcount() > 0)
{
std::cerr << "Car " << i << ": " << value << std::endl;
i++;
}
if (std::cin.gcount() > 0)
{
std::cerr << "Car " << i << ": " << value << std::endl;
std::cout.write(reinterpret_cast<char*>(&value), sizeof(value));
i++;
}
}
}
【问题讨论】:
-
不能正常工作?你期望它做什么?它做了什么?
-
似乎您甚至从未尝试从 python 代码中的标准输出读取。你期待不同的东西吗?
-
抱歉,我的代码已编辑。不幸的是,它不起作用。
标签: python c++ stdout communication stdin