如何将CSV数据从CPP发送到python脚本
我正在尝试使用CPP python绑定将CSV文件从CPP发送到python脚本,在python函数中,它打开文件并读取内容,并使用其他数据进行处理,此函数调用多次,这实际上需要更多的运行时间,因为每次函数调用中打开文件和读取文件内容都需要更多的时间,为了减少运行时间,我希望只打开文件和读取内容一次,并且每次函数调用都可以处理数据 有谁能建议最好的方法是什么?如何将CSV数据从CPP发送到python脚本,python,c++,Python,C++,我正在尝试使用CPP python绑定将CSV文件从CPP发送到python脚本,在python函数中,它打开文件并读取内容,并使用其他数据进行处理,此函数调用多次,这实际上需要更多的运行时间,因为每次函数调用中打开文件和读取文件内容都需要更多的时间,为了减少运行时间,我希望只打开文件和读取内容一次,并且每次函数调用都可以处理数据 有谁能建议最好的方法是什么? 有没有办法将文件内容从CPP传递到python?我不确定是否正确理解了您的意思,但下面是我理解您所做工作的方式。您可以使用cpp函数创建
有没有办法将文件内容从CPP传递到python?我不确定是否正确理解了您的意思,但下面是我理解您所做工作的方式。您可以使用cpp函数创建csv文件。然后用python打开并处理该文件。您已将打开和读取数据确定为程序中的瓶颈 为了避免这种情况,您可以直接将文件内容作为简单字符串传递给python(根本不涉及任何文件)。下面是一个如何使用pybind11为此类函数创建绑定的示例(创建绑定可能有更简单的方法,但到目前为止,我只使用pybind11): 请查看,特别是如何编译此类代码 使用pybind11,您可以轻松创建更复杂的返回类型绑定,例如
std::vector
。返回的对象可以将单个行存储为std::vector
。然后您甚至不必解析返回的字符串
#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}};
}
);
}
#包括
#包括
#包括
#包括
#包括
typedef VectorPairIntInt std::vector;
PYBIND11_使_不透明(标准::向量)
PYBIND11_模块(mymodule,m){
pybind11::bind_vector(m,“VectorPairIntInt”)
.def(pybind11::init())
.def(“\uuu len\uuuu”,[](const VectorPairIntInt&v){return v.size();})
.def(“\uuuu iter\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu{
返回pybind11::make_迭代器(v.begin(),v.end());
},pybind11::保持_活动();
m、 def(“获取文件内容2”,
[]()->向量pairInt{
返回{1,2}、{3,4}、{5,6};
}
);
}
注意,这段代码只是在我的头脑中编译的,可能需要调试
from mymodule import get_file_content
# read the file content
content = get_file_content()
# parse or do whatever you like with the content string ...
#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}};
}
);
}