2014-06-11 3 views
0

파이썬에서 C++로 배열을 전달하고 stdout 및 stdin을 사용하여 다시 전달해야합니다. C++에 전달할 수 있습니다. 그러나 나는 파이썬으로 다시 보낼 수 없다. stdout 모드를 설정하는 방법을 이해할 수 없다고 생각합니다. 제게 조언 해주세요. 고맙습니다. 내 파이썬 코드 :파이썬 및 C++ 통신 stdout 및 stdin

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() 

MY 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++; 
} 
} 
} 
+0

제대로 작동하지 않습니까? 무엇을 기대합니까? 대신 무엇을합니까? – univerio

+0

파이썬 코드에서 stdout을 읽지 않으려 고하는 것 같습니다. 뭔가 다른 걸 기대 했니? – univerio

+0

죄송합니다. 제 코드를 수정했습니다. 그것은 불행하게도 작동하지 않습니다. – 23454321

답변

0

)는 (통신은이 폐쇄 될 때까지 표준 출력/ERR을 읽어 백그라운드 쓰레드를 생성 한 번 방법은 표준 입력 데이터 펌프이며 프로그램 완료를 기다립니다. C++ 프로그램이 종료 될 때까지 첫 번째 communications()이 리턴하지 않으며 결과가 나온다. 완료되면

만큼 입력과 출력이 너무 큰되지 않습니다, 당신은 여전히 ​​사용 사용 및 처리 표준 출력 전에 표준 입력을 구축하여() 통신 할 수 있습니다 :

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)) 

당신이 많은 데이터를 가지고 또는 원하는 경우 더 많은 파이프 라인 -y가되도록 데이터를 stdin으로 펌핑하고 stdout에서 결과를 처리하기 위해 자신의 스레드를 생성 할 수 있습니다.