I've a question regarding boost-python. Basically I want to execute a specific python function which is stored in a std::string with boost-python. There is an example how to achieve this in the documentation: Boost python doc.
So what I'm doing is (C++ Code):
using namespace boost::python;
Py_Initialize();
// Retrieve the main module.
object main = import("__main__");
// Retrieve the main module's namespace
object global(main.attr("__dict__"));
// Define greet function in Python.
object result = exec(string_with_python_code.c_str(), global, global);
object greet = global["greet"];
//calling greet() function
greet();
Py_Finalize();
However, this also executes the code which is not in the function but in the global scope (contrary to the statement in the documentation where it says above the exec() statement: "[only] Define greet function in Python").
For example if I set the python code in string_with_python_code like this:
string_with_python_code = "print 'Hello global world!' \n"
" \n"
"def greet(): \n"
" print 'Hello local world!' \n"
" return \n";
Then the sentence "Hello global world!" is also printed out (before "Hello local world!" is printed out).
However, what I hoped to accomplish is that only the function greet() gets executed. How can I achieve this?