• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2     pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
3 
4     Copyright (c) 2017 Henry F. Schreiner
5 
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.
8 */
9 
10 #pragma once
11 
12 #include "pybind11.h"
13 
14 #include <streambuf>
15 #include <ostream>
16 #include <string>
17 #include <memory>
18 #include <iostream>
19 
20 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
PYBIND11_NAMESPACE_BEGIN(detail)21 PYBIND11_NAMESPACE_BEGIN(detail)
22 
23 // Buffer that writes to Python instead of C++
24 class pythonbuf : public std::streambuf {
25 private:
26     using traits_type = std::streambuf::traits_type;
27 
28     const size_t buf_size;
29     std::unique_ptr<char[]> d_buffer;
30     object pywrite;
31     object pyflush;
32 
33     int overflow(int c) override {
34         if (!traits_type::eq_int_type(c, traits_type::eof())) {
35             *pptr() = traits_type::to_char_type(c);
36             pbump(1);
37         }
38         return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
39     }
40 
41     // This function must be non-virtual to be called in a destructor. If the
42     // rare MSVC test failure shows up with this version, then this should be
43     // simplified to a fully qualified call.
44     int _sync() {
45         if (pbase() != pptr()) {
46 
47             {
48                 gil_scoped_acquire tmp;
49 
50                 // This subtraction cannot be negative, so dropping the sign.
51                 str line(pbase(), static_cast<size_t>(pptr() - pbase()));
52 
53                 pywrite(line);
54                 pyflush();
55 
56                 // Placed inside gil_scoped_aquire as a mutex to avoid a race
57                 setp(pbase(), epptr());
58             }
59 
60         }
61         return 0;
62     }
63 
64     int sync() override {
65         return _sync();
66     }
67 
68 public:
69 
70     pythonbuf(object pyostream, size_t buffer_size = 1024)
71         : buf_size(buffer_size),
72           d_buffer(new char[buf_size]),
73           pywrite(pyostream.attr("write")),
74           pyflush(pyostream.attr("flush")) {
75         setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
76     }
77 
78     pythonbuf(pythonbuf&&) = default;
79 
80     /// Sync before destroy
81     ~pythonbuf() override {
82         _sync();
83     }
84 };
85 
PYBIND11_NAMESPACE_END(detail)86 PYBIND11_NAMESPACE_END(detail)
87 
88 
89 /** \rst
90     This a move-only guard that redirects output.
91 
92     .. code-block:: cpp
93 
94         #include <pybind11/iostream.h>
95 
96         ...
97 
98         {
99             py::scoped_ostream_redirect output;
100             std::cout << "Hello, World!"; // Python stdout
101         } // <-- return std::cout to normal
102 
103     You can explicitly pass the c++ stream and the python object,
104     for example to guard stderr instead.
105 
106     .. code-block:: cpp
107 
108         {
109             py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
110             std::cout << "Hello, World!";
111         }
112  \endrst */
113 class scoped_ostream_redirect {
114 protected:
115     std::streambuf *old;
116     std::ostream &costream;
117     detail::pythonbuf buffer;
118 
119 public:
120     scoped_ostream_redirect(
121             std::ostream &costream = std::cout,
122             object pyostream = module_::import("sys").attr("stdout"))
123         : costream(costream), buffer(pyostream) {
124         old = costream.rdbuf(&buffer);
125     }
126 
127     ~scoped_ostream_redirect() {
128         costream.rdbuf(old);
129     }
130 
131     scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
132     scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
133     scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
134     scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
135 };
136 
137 
138 /** \rst
139     Like `scoped_ostream_redirect`, but redirects cerr by default. This class
140     is provided primary to make ``py::call_guard`` easier to make.
141 
142     .. code-block:: cpp
143 
144      m.def("noisy_func", &noisy_func,
145            py::call_guard<scoped_ostream_redirect,
146                           scoped_estream_redirect>());
147 
148 \endrst */
149 class scoped_estream_redirect : public scoped_ostream_redirect {
150 public:
151     scoped_estream_redirect(
152             std::ostream &costream = std::cerr,
153             object pyostream = module_::import("sys").attr("stderr"))
scoped_ostream_redirect(costream,pyostream)154         : scoped_ostream_redirect(costream,pyostream) {}
155 };
156 
157 
PYBIND11_NAMESPACE_BEGIN(detail)158 PYBIND11_NAMESPACE_BEGIN(detail)
159 
160 // Class to redirect output as a context manager. C++ backend.
161 class OstreamRedirect {
162     bool do_stdout_;
163     bool do_stderr_;
164     std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
165     std::unique_ptr<scoped_estream_redirect> redirect_stderr;
166 
167 public:
168     OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
169         : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
170 
171     void enter() {
172         if (do_stdout_)
173             redirect_stdout.reset(new scoped_ostream_redirect());
174         if (do_stderr_)
175             redirect_stderr.reset(new scoped_estream_redirect());
176     }
177 
178     void exit() {
179         redirect_stdout.reset();
180         redirect_stderr.reset();
181     }
182 };
183 
PYBIND11_NAMESPACE_END(detail)184 PYBIND11_NAMESPACE_END(detail)
185 
186 /** \rst
187     This is a helper function to add a C++ redirect context manager to Python
188     instead of using a C++ guard. To use it, add the following to your binding code:
189 
190     .. code-block:: cpp
191 
192         #include <pybind11/iostream.h>
193 
194         ...
195 
196         py::add_ostream_redirect(m, "ostream_redirect");
197 
198     You now have a Python context manager that redirects your output:
199 
200     .. code-block:: python
201 
202         with m.ostream_redirect():
203             m.print_to_cout_function()
204 
205     This manager can optionally be told which streams to operate on:
206 
207     .. code-block:: python
208 
209         with m.ostream_redirect(stdout=true, stderr=true):
210             m.noisy_function_with_error_printing()
211 
212  \endrst */
213 inline class_<detail::OstreamRedirect> add_ostream_redirect(module_ m, std::string name = "ostream_redirect") {
214     return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
215         .def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
216         .def("__enter__", &detail::OstreamRedirect::enter)
217         .def("__exit__", [](detail::OstreamRedirect &self_, args) { self_.exit(); });
218 }
219 
220 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
221