繁体   English   中英

我们如何将 CSV 数据从 CPP 发送到 python 脚本

[英]How can we send CSV data from CPP to python script

I am trying to send CSV file from CPP to python script with CPP python binding, In python function it does file opening and read the contents and process it with some other data, This function call happens multiple times, which is actually taking more run time因为 function 中的每个调用文件打开和读取文件内容都需要更多时间,为了减少运行时间,我只想打开文件并读取内容一次,并且每次 function 调用都会发生处理数据。

任何人都可以建议最好的方法是什么? 有没有办法将文件内容从 CPP 传递到 python?

我不确定我是否正确地理解了你,但这是我理解你在做什么的方式。 您使用 cpp function 创建 csv 文件。 然后打开并处理 python 中的文件。 您已将打开和读取数据确定为程序中的瓶颈。

为避免这种情况,您可以将文件内容作为简单字符串直接传递给 python(根本不涉及文件)。 这是一个示例,如何使用 pybind11 为此类 function 创建绑定(可能有更简单的方法来创建绑定,但到目前为止我只使用过 pybind11):

#include <pybind11/pybind11.h>
#include <string>

namespace py = pybind11;

PYBIND11_MODULE(mymodule, m) {

    m.def("get_file_content",
        []() {
            // This string needs to be UTF-8 encoded
            return std::string("1,2\n3,4\n5,6");
        }
    );
}

这将创建一个 function 可以在 python 中使用,如下所示:

from mymodule import get_file_content

# read the file content
content = get_file_content()

# parse or do whatever you like with the content string ...

查看文档,尤其是如何编译此类代码。

使用 pybind11,您可以轻松地创建绑定更复杂的返回类型,例如std::vector<std::vector<int>> 返回的 object 可以将各个行存储为std::vector<int> 然后你甚至不必解析返回的字符串。

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>

#include <vector>
#include <tuple>

typedef VectorPairIntInt std::vector<std::pair<int,int>>;

PYBIND11_MAKE_OPAQUE(std::vector<std::pair<int,int>>)

PYBIND11_MODULE(mymodule, m) {
    pybind11::bind_vector<VectorPairIntInt>(m, "VectorPairIntInt")
        .def(pybind11::init<>())
        .def("__len__", [](const VectorPairIntInt &v) { return v.size(); })
        .def("__iter__", [](VectorPairIntInt &v) {
            return pybind11::make_iterator(v.begin(), v.end());
        }, pybind11::keep_alive<0, 1>());

    m.def("get_file_content2",
        []() -> VectorPairIntInt {
           return {{1,2},{3,4},{5,6}};
        }
    );
}

请注意,此代码仅在我的脑海中编译,可能需要调试。

暂无
暂无

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

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