Reputation: 427
I am writing a python embedding in C++ application. The related code snippet that I declare the module of python(user-defined one) that needs to be embedded as below:
boost::python::object main_module = boost::python::import("__main__");
boost::python::object main_namespace = main_module.attr("__dict__");
boost::python::exec("import python_module", main_namespace); //This line is the culprit
However, I'm stuck when I receive the following error:
terminate called after throwing an instance of 'boost::python::error_already_set'
My user-defined python module resides in the same directory as my C++ code. When I try like to use numpy
that works, the problem is that only with my user-defined one, it doesn't. What could be done in order to debug it?
EDIT:
After I include the code in try/catch block, I obtained the following compile error:
ImportError: No module named python_module
I also try to add this:
boost::python::exec("import sys; sys.path.append('/path/to/python_module.py');", main_namespace);
boost::python::exec("import python_module", main_namespace);
but not yet working.
The problem now is how do I make it known to my C++ code?
Upvotes: 1
Views: 1051
Reputation: 5279
You can try a couple of things:
In your C++ app: boost::python::exec("import sys; sys.path.append('/path/to'); import python_module; del sys"), main_namespace);
, or
In your shell: cd /path/to; call-your-c++-app
. Then, in C++, you would need only to boost::python::exec("import python_module");
, or
Set your environment variable to export PYTHONPATH=/path/to:${PYTHONPATH}
and execute your program. Your C++ in this case would need only to boost::python::exec("import python_module");
as in the above solution.
The issue: You need to append the path leading to the module to sys.path
and not the path to the module file itself.
Another hint: by default, Python will load modules from the current directory. If you cd
there and execute your application from that directory, it should find the module on the current directory.
Upvotes: 1