[英]embedding python in c++: python script not recognized
I am trying to embed python script into c++ project. 我试图将python脚本嵌入到c ++项目中。 Below is what I have tried so far. 以下是我到目前为止所尝试的内容。
#include<iostream>
#include <Python.h>
int
main()
{
Py_Initialize();
PyObject* sysPath = PySys_GetObject("path");
PyObject* modPath = PyBytes_FromString("C:\\Users\\naal\\Documents\\Visual Studio 2017\\Projects\\Project1\pyscripts");
int result = PyList_Insert(sysPath,0, modPath);
PyObject *pModule = PyImport_ImportModule("myscript2");
printf("%p\n", pModule);
return 0;
}
below is the python script "myscript2.py" 下面是python脚本“myscript2.py”
def find_me():
print("hey you found me")
The problem is, the main module is not able to find the python script ie object pyModule is always NULL, no matter how I change python script path. 问题是,主模块无法找到python脚本,即对象pyModule始终为NULL,无论我如何更改python脚本路径。
What am I doing wrong ? 我究竟做错了什么 ?
I ended up implementing this in another way. 我最后以另一种方式实现了这一点。
#include<iostream>
#include <Python.h>
int main() {
std::string location = "C:\\Users\\myscript.py";
const char* file_location = location.c_str(); FILE* file_pointer;
Py_Initialize();
file_pointer = _Py_fopen(file_location, "r");
PyRun_SimpleFile(file_pointer, file_location);
Py_Finalize();
return 1;
}
The above seemed to work. 以上似乎都有效。 I still don't know why the SYSPATH idea originially mentioned in the question didn't work. 我仍然不知道为什么在问题中原始提到的SYSPATH想法不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.