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