Python和C ++通信stdout和stdin

时间:2014-06-11 01:55:55

标签: python c++ stdout communication stdin

我必须将数组从Python传递到C ++并使用stdout和stdin返回。我可以把它传递给C ++。但是我不能把它发送回python。我想我不明白如何设置stdout模式。请给我建议。谢谢。 我的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++;
}
}
}

1 个答案:

答案 0 :(得分:0)

communic()是一种一次性方法,它创建后台线程来读取stdout / err,直到它们关闭,将数据泵送到stdin并等待程序完成。你这样做的方式,第一个communication()不会返回,直到C ++程序终止,之后没有任何结果产生任何结果。

只要输入和输出不是太大,你仍然可以在使用之前通过构建stdin并在完成时处理stdout来使用communication():

import struct
import subprocess
from cStringIO import StringIO

stdin_buf = StringIO()
array = [1.0 for _ in range(10)]
for item in array:
    stdin_buf.write(struct.pack('<f', item))

proc = subprocess.Popen(['test.exe'], stdin=subprocess.PIPE, stdout = subprocess.PIPE)
out, err = proc.communicate(stdin_buf.getvalue())

# assuming the result comes back the same way it went in...
item_len = struct.calcsize('<f')
stdout_buf = StringIO(out)
stdout_buf.seek(0)
for i in range(len(out)/item_len):
    val = struct.unpack('<f', stdout_buf.read(4))

如果您有大量数据或想要更多管道,您可以创建自己的线程以将数据泵入stdin并在stdout上处理结果。