exec.qbk 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. [section boost/python/exec.hpp]
  2. [section Introduction]
  3. Exposes a mechanism for embedding the python interpreter into C++ code.
  4. [endsect]
  5. [section Function `eval`]
  6. ``
  7. object 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. ``
  18. object 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. ``
  29. object 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]
  39. The following example demonstrates the use of import and exec to define a function in python, and later call it from within C++.
  40. ``
  41. #include <iostream>
  42. #include <string>
  43. using namespace boost::python;
  44. void greet()
  45. {
  46. // Retrieve the main module.
  47. object main = import("__main__");
  48. // Retrieve the main module's namespace
  49. object global(main.attr("__dict__"));
  50. // Define greet function in Python.
  51. object result = exec(
  52. "def greet(): \n"
  53. " return 'Hello from Python!' \n",
  54. global, global);
  55. // Create a reference to it.
  56. object greet = global["greet"];
  57. // Call it.
  58. std::string message = extract<std::string>(greet());
  59. std::cout << message << std::endl;
  60. }
  61. ``
  62. Instead of embedding the python script into a string, we could also store it in an a file...
  63. ``
  64. def greet():
  65. return 'Hello from Python!'
  66. ``
  67. ... and execute that instead.
  68. ``
  69. // ...
  70. // Load the greet function from a file.
  71. object result = exec_file(script, global, global);
  72. // ...
  73. }
  74. ``
  75. [endsect]
  76. [endsect]