C++ I/O with Python
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 Pytho开发者_StackOverflow社区n List . How do I do that ?
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()]
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.
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.)
In the command for the process you could do a redirect to a temporary file. Then read that file when the process returns.
精彩评论