Python的C++ I/O

2024-05-02 20:04:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中编写了一个模块,它使用子过程模块运行C++程序。一旦我从C++得到输出,我需要把它存储在Python列表中。我该怎么做?在


Tags: 模块程序列表过程
3条回答

一种肮脏的方法:

您可以使用Python从stdin读取(raw_input)(如果没有输入,它将等待)。C++程序写入STDUT。在

这是我用过的一个又快又脏的方法。在

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

根据您的评论,假设data包含输出:

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

我假设数字是用空白分隔的,并且你已经从C++程序中得到了Python中的字符串(即,你知道如何使用^ {CD2>}模块)。在

<> E>编辑< EEM>:让我们说你的C++程序是:

^{pr2}$

然后,可以在Python中执行以下操作:

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

(无论你的C++程序输出的是换行符,或者是空白的任何组合)。

相关问题 更多 >