blob: 442d0e9c9180f5ca1d4d7340733d37b007c49e64 [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Utilities
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);
Dean Moldovan194d8b92017-03-29 00:27:56 +020058
59C++11 raw string literals are also supported and quite handy for this purpose.
60The only requirement is that the first statement must be on a new line following
61the raw string delimiter ``R"(``, ensuring all lines have common leading indent:
62
63.. code-block:: cpp
64
65 py::eval<py::eval_statements>(R"(
66 x = get_answer()
67 if x == 42:
68 print('Hello World!')
69 else:
70 print('Bye!')
71 )", scope
72 );