• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1[section boost/python/exec.hpp]
2[section Introduction]
3Exposes a mechanism for embedding the python interpreter into C++ code.
4[endsect]
5[section Function `eval`]
6``
7object eval(str expression,
8            object globals = object(),
9            object locals = object());
10``
11[variablelist
12[[Effects][Evaluate Python expression from expression in the context specified by the dictionaries globals and locals. ]]
13[[Returns][An instance of object which holds the value of the expression.]]
14]
15[endsect]
16[section Function `exec`]
17``
18object exec(str code,
19            object globals = object(),
20            object locals = object());
21``
22[variablelist
23[[Effects][Execute Python source code from code in the context specified by the dictionaries globals and locals. ]]
24[[Returns][ An instance of object which holds the result of executing the code. ]]
25]
26[endsect]
27[section Function `exec_file`]
28``
29object exec_file(str filename,
30                 object globals = object(),
31                 object locals = object());
32``
33[variablelist
34[[Effects][Execute Python source code from the file named by filename in the context specified by the dictionaries globals and locals.]]
35[[Returns][An instance of object which holds the result of executing the code. ]]
36]
37[endsect]
38[section Examples]
39The following example demonstrates the use of import and exec to define a function in python, and later call it from within C++.
40
41``
42#include <iostream>
43#include <string>
44
45using namespace boost::python;
46
47void greet()
48{
49  // Retrieve the main module.
50  object main = import("__main__");
51
52  // Retrieve the main module's namespace
53  object global(main.attr("__dict__"));
54
55  // Define greet function in Python.
56  object result = exec(
57    "def greet():                   \n"
58    "   return 'Hello from Python!' \n",
59    global, global);
60
61  // Create a reference to it.
62  object greet = global["greet"];
63
64  // Call it.
65  std::string message = extract<std::string>(greet());
66  std::cout << message << std::endl;
67}
68 ``
69 Instead of embedding the python script into a string, we could also store it in an a file...
70``
71def greet():
72   return 'Hello from Python!'
73``
74 ... and execute that instead.
75
76``
77  // ...
78  // Load the greet function from a file.
79  object result = exec_file(script, global, global);
80  // ...
81}
82``
83[endsect]
84[endsect]
85