tags:

views:

127

answers:

4

I am writing a module in Python which runs a C++ Program using subprocess module. Once I get the output from C++, I need to store the that in Python List . How do I do that ?

+3  A: 

one dirty method:

You can use Python to read (raw_input) from stdin (if there is not input, it will wait). the C++ program writes to stdout.

Yin Zhu
+1  A: 

Based upon your comment, assuming data contains the output:

numbers = [int(x) for x in data.split()]

I am assuming that the numbers are separated by whitespace, and that you already got the string in Python from your C++ program (i.e., you know how to use the subprocess module).

Edit: Let's say your C++ program is:

$ cat a.cpp
#include <iostream>

int main()
{
    int a[] = { 1, 2, 3, 4 };
    for (int i=0; i < sizeof a / sizeof a[0]; ++i) {
            std::cout << a[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}
$ g++ a.cpp -o test
$ ./test
1 2 3 4
$

Then, you can do this in Python:

import subprocess
data = subprocess.Popen('./test', stdout=subprocess.PIPE).communicate()[0]
numbers = [int(x) for x in data.split()]

(It doesn't matter if your C++ program outputs the numbers with newline as a separator, or any combination of white-space for that matter.)

Alok
My Doubt is about accessing an array in C++ as a list in Python.Ok So How do I access a C++ array from Python
vishwanath Katharki
You need to print the array from C++ to `stdout` (using `std::cout` for example). Then, use `subprocess.Popen()` to communicate with your C++ program, and then get the numbers as above.
Alok
Dude, I guess You Misinterpreted.Python module runs C++ program using Subprocess. C++ outputs an array. I need to catch that output in Python module without using temp storage
vishwanath Katharki
Dude, he's telling you exactly what you need to do. Your C++ program is outputing *text*. Python is reading the data as text.
Brian Neal
+6  A: 

Here is a quick and dirty method that I have used.

def run_cpp_thing(parameters):

    proc = subprocess.Popen('mycpp' + parameters,
                        shell=True,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        stdin=subprocess.PIPE)

    so, se = proc.communicate()

    # print se # the stderr stream
    # print so # the stdio stream

    # I'm going to assume so = 
    #    "1 2 3 4 5"

    # Now parse the stdio stream. 
    # you will obvious do much more error checking :)
    # **updated to make them all numbers**
    return [float(x) for x in so.next().split()]
James Brooks
A: 

In the command for the process you could do a redirect to a temporary file. Then read that file when the process returns.

telliott99