1

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 numpythat 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?

1 Answer 1

1

You can try a couple of things:

  1. In your C++ app: boost::python::exec("import sys; sys.path.append('/path/to'); import python_module; del sys"), main_namespace);, or

  2. 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

  3. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.