简体   繁体   English

一个非常简单的python subprocess.Popen任务带来的无尽问题

[英]Endless problems with a very simple python subprocess.Popen task

I'd like python to send around a half-million integers in the range 0-255 each to an executable written in C++. 我希望python将大约50万个整数(范围在0-255之间)发送给用C ++编写的可执行文件。 This executable will then respond with a few thousand integers. 然后,该可执行文件将以几千个整数响应。 Each on one line. 每一行。 This seems like it should be very simple to do with subprocess but i've had endless troubles. 看起来子过程应该很简单,但是我遇到了无数麻烦。 Right now im testing with code: 现在用代码进行即时测试:

// main()
u32 num;
std::cin >> num;

u8* data = new u8[num];
for (u32 i = 0; i < num; ++i)
    std::cin >> data[i];

// test output / spit it back out
for (u32 i = 0; i < num; ++i)
    std::cout << data[i] << std::endl;

return 0;

Building an array of strings ("data"), each like "255\\n", in python and then using: 在python中构建一个字符串数组(“数据”),每个字符串都类似于“ 255 \\ n”,然后使用:

output = proc.communicate("".join(data))[0]

...doesn't work (says stdin is closed, maybe too much at one time). ...不起作用(例如stdin已关闭,一次可能太多)。 Neither has using proc.stdin and proc.stdout worked. 使用proc.stdin和proc.stdout都不起作用。 This should be so very simple, but I'm getting constant exceptions, and/or no output data returned to me. 这应该非常简单,但是我不断遇到异常,并且/或者没有输出数据返回给我。 My Popen is currently: 我的Popen当前是:

proc = Popen('aux/test_cpp_program', stdin=PIPE, stdout=PIPE, bufsize=1)

Advise me before I pull my hair out. 在我拔头发之前先给我建议。 ;) ;)

This works perfectly for me: 这对我来说非常合适:

#include <iostream>

int main()
{
    int num;
    std::cin >> num;

    char* data = new char[num];
    for (int i = 0; i < num; ++i)
        std::cin >> data[i];

    // test output / spit it back out
    for (int i = 0; i < num; ++i)
        std::cout << data[i] << std::endl;

    return 0;
}

python: 蟒蛇:

In [9]: from subprocess import Popen, PIPE
In [10]: a = Popen('./a.out', stdin=PIPE, stdout=PIPE)
In [11]: a.stdin.write("2\nab")
In [12]: a.stdout.read()
Out[12]: 'a\nb\n'

Note that I added a delimiter (\\n) between the number of bytes to write, this is the safest if you do not want your c++ cin to fail on sending something like 3,1,2,3 which would concatenate to 3123, expecting so many arguments. 请注意,我在要写入的字节数之间添加了一个定界符(\\ n),这是最安全的,如果您不希望c ++ cin在发送诸如3、1、2、3之类的东西时会失败,它们会连接到3123,期望这么多争论。

In C++, when you read a char or unsigned char from cin , it reads a single byte from stdin . 在C ++中,当您从cin读取charunsigned char时,它将从stdin读取单个字节。 However, you expect it to read a decimal representation of a number from 0 to 255. If you read an int instead it should read it correctly: 但是,您希望它读取从0到255的数字的十进制表示形式。如果您读取一个int则它应该正确读取它:

unsigned int n;
std::cin >> n;
data[i] = static_cast<u8>(n);

Or instead, you can have the Python code write the values as a sequence of bytes rather than digits, by using the chr function. 或者,您可以使用chr函数让Python代码将值以字节而不是数字的顺序写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM