###

# Boost.Python

## Header <boost/python/exec.hpp>

## Contents

Introduction
Functions
  `eval`
  `exec`
  `exec_file`
Examples

## Introduction

Exposes a mechanism for embedding the python interpreter into C++ code.

## Functions

### `eval`

    object eval(str expression,
                object globals = object(),
                object locals = object());

Effects: Evaluate Python expression from `expression` in the context specified by the dictionaries `globals` and `locals`.
Returns: An instance of object which holds the value of the expression.

### `exec`

    object exec(str code,
                object globals = object(),
                object locals = object());

Effects: Execute Python source code from `code` in the context specified by the dictionaries `globals` and `locals`.
Returns: An instance of object which holds the result of executing the code.

### `exec_file`

    object exec_file(str filename,
                     object globals = object(),
                     object locals = object());

Effects: Execute Python source code from the file named by `filename` in the context specified by the dictionaries `globals` and `locals`.
Returns: An instance of object which holds the result of executing the code.

## Examples

<para>The following example demonstrates the use of <function>import</function> and <function>exec</function> to define a function in python, and later call it from within C++.</para>

    #include <iostream>
    #include <string>

    using namespace boost::python;

    void greet()
    {
      // 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(
        "def greet(self):               \n"
        "   return 'Hello from Python!' \n",
        global, global);

      // Create a reference to it.
      object greet = global["greet"];

      // Call it.
      std::string message = extract<std::string>(greet());
      std::cout << message << std::endl;
    }

<para>Instead of embedding the python script into a string, we could also store it in an a file...</para>

    def greet(self):
       return 'Hello from Python!'

<para>... and execute that instead.</para>

      // ...
      // Load the greet function from a file.
      object result = exec_file(script, global, global);
      // ...
    }

Revised 01 November, 2005

© Copyright Stefan Seefeld 2005.