KO70
KO70

Reputation: 187

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

Upvotes: 4

Views: 2747

Answers (2)

killdaclick
killdaclick

Reputation: 731

Everything in global scope will be executed if you import python module either using interpreter or Python C API / BOOST Python. Thats how python works.

To fix this add this before global scope:

if __name__ == "__main__":

Example:

*script.py*

def local():
    print "local"

if __name__ == "__main__":
    print "global"

If you execute script only "global" will be printed. If you import this module nothing will be printed.

Upvotes: 0

Borealid
Borealid

Reputation: 98489

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.

Upvotes: 3

Related Questions