CE70 CE70 - 3 months ago 36
C++ Question

Execute python function with boost-python (not global scope statements)

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;

// 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


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?


A Python function definition is an execution of Python code. So is a Python module import: importing a module can cause arbitrary Python statements to run.

The way to not run code outside your function definition is to not pass code outside your function definition to exec. exec will do exactly what you tell it to do, no less.