我有这样的cpp代码:
void callPython() {
Py_Initialize();
PyObject* sysPath = PySys_GetObject("path");
PyList_Append(sysPath, PyUnicode_FromString("/jarvis_repo/src/cpp/packages/jarvis/nlp/"));
// Load the module
PyObject *pName = PyUnicode_FromString("my_mod");
PyObject *pModule = PyImport_Import(pName);
if (pModule != NULL) {
std::cout << "Python module found\n";
PyObject* pFunc = PyObject_GetAttrString(pModule, "my_func");
if(pFunc != NULL){
PyObject_CallObject(pFunc, NULL);
} else {
std::cout << "Couldn't find func\n";
}
}
else {
PyErr_Print();
std::cout << "Python Module not found\n";
}
Py_Finalize();
}
我在同一目录/jarvis_repo/src/cpp/packages/jarvis/nlp/
中还有两个文件my_mod.py和test.py,如下所示:
my_mod.py
from test import coreDM
def my_func():
print("my_func() got called")
coreDM()
test.py
class coreDM():
def __init__(self):
print("Initialized test")
def print_message():
print("Hello from coreDM")
从from test import coreDM
中省略coreDM()
和my_mod.py
时,
PyImport_Import可以正常工作并打印my_func() got called
,否则返回NULL。有任何想法可能会发生这种情况吗?
预先感谢!
错误消息:
ImportError: cannot import name 'coreDM'
Python Module not found
答案 0 :(得分:1)
使用ProductDTO
代替$id = 1;
$offset = 0;
$limit = 5;
$stmt = $this->conn->prepare("SELECT * FROM users where id !=:id ORDER BY first_name LIMIT :offset, :limit");
$stmt->execute([':id'=>$id,':limit' => $limit, ':offset' => $offset]);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($data);
exit;
,以从所需位置导入测试。
@DavidW提到,核心库中有一个名为PyList_Insert
的可导入模块。
更改
PyList_Append
到
test
因此PyList_Append(sysPath, PyUnicode_FromString("/jarvis_repo/src/cpp/packages/jarvis/nlp/"));
模块首先在 / jarvis_repo / src / cpp / packages / jarvis / nlp / 中找到,而不是在核心库中找到。
注意:您应该改名为PyList_Insert(sysPath, 0, PyUnicode_FromString("/jarvis_repo/src/cpp/packages/jarvis/nlp/"));