2 pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
4 Copyright (c) 2017 Henry F. Schreiner
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
20 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
21 NAMESPACE_BEGIN(detail)
23 // Buffer that writes to Python instead of C++
24 class pythonbuf : public std::streambuf {
26 using traits_type = std::streambuf::traits_type;
33 if (!traits_type::eq_int_type(c, traits_type::eof())) {
34 *pptr() = traits_type::to_char_type(c);
37 return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
41 if (pbase() != pptr()) {
42 // This subtraction cannot be negative, so dropping the sign
43 str line(pbase(), static_cast<size_t>(pptr() - pbase()));
48 setp(pbase(), epptr());
54 pythonbuf(object pyostream)
55 : pywrite(pyostream.attr("write")),
56 pyflush(pyostream.attr("flush")) {
57 setp(d_buffer, d_buffer + sizeof(d_buffer) - 1);
60 /// Sync before destroy
70 This a move-only guard that redirects output.
74 #include <pybind11/iostream.h>
79 py::scoped_ostream_redirect output;
80 std::cout << "Hello, World!"; // Python stdout
81 } // <-- return std::cout to normal
83 You can explicitly pass the c++ stream and the python object,
84 for example to guard stderr instead.
89 py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
90 std::cerr << "Hello, World!";
93 class scoped_ostream_redirect {
96 std::ostream &costream;
97 detail::pythonbuf buffer;
100 scoped_ostream_redirect(
101 std::ostream &costream = std::cout,
102 object pyostream = module::import("sys").attr("stdout"))
103 : costream(costream), buffer(pyostream) {
104 old = costream.rdbuf(&buffer);
107 ~scoped_ostream_redirect() {
111 scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
112 scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
113 scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
114 scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
119 Like `scoped_ostream_redirect`, but redirects cerr by default. This class
120 is provided primary to make ``py::call_guard`` easier to make.
124 m.def("noisy_func", &noisy_func,
125 py::call_guard<scoped_ostream_redirect,
126 scoped_estream_redirect>());
129 class scoped_estream_redirect : public scoped_ostream_redirect {
131 scoped_estream_redirect(
132 std::ostream &costream = std::cerr,
133 object pyostream = module::import("sys").attr("stderr"))
134 : scoped_ostream_redirect(costream,pyostream) {}
138 NAMESPACE_BEGIN(detail)
140 // Class to redirect output as a context manager. C++ backend.
141 class OstreamRedirect {
144 std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
145 std::unique_ptr<scoped_estream_redirect> redirect_stderr;
148 OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
149 : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
153 redirect_stdout.reset(new scoped_ostream_redirect());
155 redirect_stderr.reset(new scoped_estream_redirect());
159 redirect_stdout.reset();
160 redirect_stderr.reset();
164 NAMESPACE_END(detail)
167 This is a helper function to add a C++ redirect context manager to Python
168 instead of using a C++ guard. To use it, add the following to your binding code:
172 #include <pybind11/iostream.h>
176 py::add_ostream_redirect(m, "ostream_redirect");
178 You now have a Python context manager that redirects your output:
180 .. code-block:: python
182 with m.ostream_redirect():
183 m.print_to_cout_function()
185 This manager can optionally be told which streams to operate on:
187 .. code-block:: python
189 with m.ostream_redirect(stdout=true, stderr=true):
190 m.noisy_function_with_error_printing()
193 inline class_<detail::OstreamRedirect> add_ostream_redirect(module m, std::string name = "ostream_redirect") {
194 return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
195 .def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
196 .def("__enter__", &detail::OstreamRedirect::enter)
197 .def("__exit__", [](detail::OstreamRedirect &self, args) { self.exit(); });
200 NAMESPACE_END(PYBIND11_NAMESPACE)