C++与Python的I/O
我正在用Python写一个模块,这个模块会通过subprocess模块运行一个C++程序。一旦我从C++程序得到输出,我需要把这些输出存储到Python的列表里。我该怎么做呢?
4 个回答
1
根据你的评论,假设 data
包含了输出内容:
numbers = [int(x) for x in data.split()]
我假设这些数字是用空格分开的,并且你已经从你的 C++ 程序中得到了这个字符串(也就是说,你知道怎么使用 subprocess
模块)。
编辑:假设你的 C++ 程序是:
$ 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
$
那么,你可以在 Python 中这样做:
import subprocess
data = subprocess.Popen('./test', stdout=subprocess.PIPE).communicate()[0]
numbers = [int(x) for x in data.split()]
(无论你的 C++ 程序是用换行符还是其他空白字符来分隔数字,这都没关系。)
2
有一种简单的方法:
你可以用Python来从标准输入(stdin)读取数据(使用raw_input),如果没有输入的话,它会一直等待。C++程序则是把结果输出到标准输出(stdout)。
6
这是我用过的一种简单粗暴的方法。
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()]