You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.5 KiB

  1. Utilities
  2. #########
  3. Using Python's print function in C++
  4. ====================================
  5. The usual way to write output in C++ is using ``std::cout`` while in Python one
  6. would use ``print``. Since these methods use different buffers, mixing them can
  7. lead to output order issues. To resolve this, pybind11 modules can use the
  8. :func:`py::print` function which writes to Python's ``sys.stdout`` for consistency.
  9. Python's ``print`` function is replicated in the C++ API including optional
  10. keyword arguments ``sep``, ``end``, ``file``, ``flush``. Everything works as
  11. expected in Python:
  12. .. code-block:: cpp
  13. py::print(1, 2.0, "three"); // 1 2.0 three
  14. py::print(1, 2.0, "three", "sep"_a="-"); // 1-2.0-three
  15. auto args = py::make_tuple("unpacked", true);
  16. py::print("->", *args, "end"_a="<-"); // -> unpacked True <-
  17. .. _eval:
  18. Evaluating Python expressions from strings and files
  19. ====================================================
  20. pybind11 provides the `eval`, `exec` and `eval_file` functions to evaluate
  21. Python expressions and statements. The following example illustrates how they
  22. can be used.
  23. .. code-block:: cpp
  24. // At beginning of file
  25. #include <pybind11/eval.h>
  26. ...
  27. // Evaluate in scope of main module
  28. py::object scope = py::module::import("__main__").attr("__dict__");
  29. // Evaluate an isolated expression
  30. int result = py::eval("my_variable + 10", scope).cast<int>();
  31. // Evaluate a sequence of statements
  32. py::exec(
  33. "print('Hello')\n"
  34. "print('world!');",
  35. scope);
  36. // Evaluate the statements in an separate Python file on disk
  37. py::eval_file("script.py", scope);
  38. C++11 raw string literals are also supported and quite handy for this purpose.
  39. The only requirement is that the first statement must be on a new line following
  40. the raw string delimiter ``R"(``, ensuring all lines have common leading indent:
  41. .. code-block:: cpp
  42. py::exec(R"(
  43. x = get_answer()
  44. if x == 42:
  45. print('Hello World!')
  46. else:
  47. print('Bye!')
  48. )", scope
  49. );
  50. .. note::
  51. `eval` and `eval_file` accept a template parameter that describes how the
  52. string/file should be interpreted. Possible choices include ``eval_expr``
  53. (isolated expression), ``eval_single_statement`` (a single statement, return
  54. value is always ``none``), and ``eval_statements`` (sequence of statements,
  55. return value is always ``none``). `eval` defaults to ``eval_expr``,
  56. `eval_file` defaults to ``eval_statements`` and `exec` is just a shortcut
  57. for ``eval<eval_statements>``.