【问题标题】:Python and C++ communication stdout and stdinPython 和 C++ 通信标准输出和标准输入
【发布时间】: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


【解决方案1】:

communicate() 是一种一次性方法,它创建后台线程来读取 stdout/err 直到它们被关闭,将数据泵送到 stdin 并等待程序完成。按照您的操作方式,第一个通信()在 C++ 程序终止之前不会返回,之后不会产生任何结果。

只要输入和输出不是太大,您仍然可以通过在使用前构建标准输入并在完成后处理标准输出来使用communicate():

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2012-02-23
    • 2013-06-13
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多