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.

57 lines
2.0 KiB

8 years ago
  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. Evaluating Python expressions from strings and files
  18. ====================================================
  19. pybind11 provides the :func:`eval` and :func:`eval_file` functions to evaluate
  20. Python expressions and statements. The following example illustrates how they
  21. can be used.
  22. Both functions accept a template parameter that describes how the argument
  23. should be interpreted. Possible choices include ``eval_expr`` (isolated
  24. expression), ``eval_single_statement`` (a single statement, return value is
  25. always ``none``), and ``eval_statements`` (sequence of statements, return value
  26. is always ``none``).
  27. .. code-block:: cpp
  28. // At beginning of file
  29. #include <pybind11/eval.h>
  30. ...
  31. // Evaluate in scope of main module
  32. py::object scope = py::module::import("__main__").attr("__dict__");
  33. // Evaluate an isolated expression
  34. int result = py::eval("my_variable + 10", scope).cast<int>();
  35. // Evaluate a sequence of statements
  36. py::eval<py::eval_statements>(
  37. "print('Hello')\n"
  38. "print('world!');",
  39. scope);
  40. // Evaluate the statements in an separate Python file on disk
  41. py::eval_file("script.py", scope);