iostream.h revision 14299
112855Sgabeblack@google.com/*
212855Sgabeblack@google.com    pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
312855Sgabeblack@google.com
412855Sgabeblack@google.com    Copyright (c) 2017 Henry F. Schreiner
512855Sgabeblack@google.com
612855Sgabeblack@google.com    All rights reserved. Use of this source code is governed by a
712855Sgabeblack@google.com    BSD-style license that can be found in the LICENSE file.
812855Sgabeblack@google.com*/
912855Sgabeblack@google.com
1012855Sgabeblack@google.com#pragma once
1112855Sgabeblack@google.com
1212855Sgabeblack@google.com#include "pybind11.h"
1312855Sgabeblack@google.com
1412855Sgabeblack@google.com#include <streambuf>
1512855Sgabeblack@google.com#include <ostream>
1612855Sgabeblack@google.com#include <string>
1712855Sgabeblack@google.com#include <memory>
1812855Sgabeblack@google.com#include <iostream>
1912855Sgabeblack@google.com
2012855Sgabeblack@google.comNAMESPACE_BEGIN(PYBIND11_NAMESPACE)
2112855Sgabeblack@google.comNAMESPACE_BEGIN(detail)
2212855Sgabeblack@google.com
2312855Sgabeblack@google.com// Buffer that writes to Python instead of C++
2412855Sgabeblack@google.comclass pythonbuf : public std::streambuf {
2512855Sgabeblack@google.comprivate:
2612855Sgabeblack@google.com    using traits_type = std::streambuf::traits_type;
2712855Sgabeblack@google.com
2812855Sgabeblack@google.com    const size_t buf_size;
2912855Sgabeblack@google.com    std::unique_ptr<char[]> d_buffer;
3012855Sgabeblack@google.com    object pywrite;
3112855Sgabeblack@google.com    object pyflush;
3212855Sgabeblack@google.com
3312855Sgabeblack@google.com    int overflow(int c) {
3412855Sgabeblack@google.com        if (!traits_type::eq_int_type(c, traits_type::eof())) {
3512855Sgabeblack@google.com            *pptr() = traits_type::to_char_type(c);
3612855Sgabeblack@google.com            pbump(1);
3712855Sgabeblack@google.com        }
3812855Sgabeblack@google.com        return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
3912855Sgabeblack@google.com    }
4012855Sgabeblack@google.com
4112855Sgabeblack@google.com    int sync() {
4212855Sgabeblack@google.com        if (pbase() != pptr()) {
4312855Sgabeblack@google.com            // This subtraction cannot be negative, so dropping the sign
4412855Sgabeblack@google.com            str line(pbase(), static_cast<size_t>(pptr() - pbase()));
4512855Sgabeblack@google.com
4612855Sgabeblack@google.com            {
4712855Sgabeblack@google.com                gil_scoped_acquire tmp;
4812855Sgabeblack@google.com                pywrite(line);
4912855Sgabeblack@google.com                pyflush();
5012855Sgabeblack@google.com            }
5112855Sgabeblack@google.com
5212855Sgabeblack@google.com            setp(pbase(), epptr());
5312855Sgabeblack@google.com        }
5412855Sgabeblack@google.com        return 0;
5512855Sgabeblack@google.com    }
5612855Sgabeblack@google.com
5712855Sgabeblack@google.compublic:
5812855Sgabeblack@google.com
5912855Sgabeblack@google.com    pythonbuf(object pyostream, size_t buffer_size = 1024)
6012855Sgabeblack@google.com        : buf_size(buffer_size),
6112855Sgabeblack@google.com          d_buffer(new char[buf_size]),
6212855Sgabeblack@google.com          pywrite(pyostream.attr("write")),
6312855Sgabeblack@google.com          pyflush(pyostream.attr("flush")) {
6412855Sgabeblack@google.com        setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
6512855Sgabeblack@google.com    }
6612855Sgabeblack@google.com
6712855Sgabeblack@google.com    pythonbuf(pythonbuf&&) = default;
6812855Sgabeblack@google.com
6912855Sgabeblack@google.com    /// Sync before destroy
7012855Sgabeblack@google.com    ~pythonbuf() {
7112855Sgabeblack@google.com        sync();
7212855Sgabeblack@google.com    }
7312855Sgabeblack@google.com};
7412855Sgabeblack@google.com
7512855Sgabeblack@google.comNAMESPACE_END(detail)
7612855Sgabeblack@google.com
7712855Sgabeblack@google.com
78/** \rst
79    This a move-only guard that redirects output.
80
81    .. code-block:: cpp
82
83        #include <pybind11/iostream.h>
84
85        ...
86
87        {
88            py::scoped_ostream_redirect output;
89            std::cout << "Hello, World!"; // Python stdout
90        } // <-- return std::cout to normal
91
92    You can explicitly pass the c++ stream and the python object,
93    for example to guard stderr instead.
94
95    .. code-block:: cpp
96
97        {
98            py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
99            std::cerr << "Hello, World!";
100        }
101 \endrst */
102class scoped_ostream_redirect {
103protected:
104    std::streambuf *old;
105    std::ostream &costream;
106    detail::pythonbuf buffer;
107
108public:
109    scoped_ostream_redirect(
110            std::ostream &costream = std::cout,
111            object pyostream = module::import("sys").attr("stdout"))
112        : costream(costream), buffer(pyostream) {
113        old = costream.rdbuf(&buffer);
114    }
115
116    ~scoped_ostream_redirect() {
117        costream.rdbuf(old);
118    }
119
120    scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
121    scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
122    scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
123    scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
124};
125
126
127/** \rst
128    Like `scoped_ostream_redirect`, but redirects cerr by default. This class
129    is provided primary to make ``py::call_guard`` easier to make.
130
131    .. code-block:: cpp
132
133     m.def("noisy_func", &noisy_func,
134           py::call_guard<scoped_ostream_redirect,
135                          scoped_estream_redirect>());
136
137\endrst */
138class scoped_estream_redirect : public scoped_ostream_redirect {
139public:
140    scoped_estream_redirect(
141            std::ostream &costream = std::cerr,
142            object pyostream = module::import("sys").attr("stderr"))
143        : scoped_ostream_redirect(costream,pyostream) {}
144};
145
146
147NAMESPACE_BEGIN(detail)
148
149// Class to redirect output as a context manager. C++ backend.
150class OstreamRedirect {
151    bool do_stdout_;
152    bool do_stderr_;
153    std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
154    std::unique_ptr<scoped_estream_redirect> redirect_stderr;
155
156public:
157    OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
158        : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
159
160    void enter() {
161        if (do_stdout_)
162            redirect_stdout.reset(new scoped_ostream_redirect());
163        if (do_stderr_)
164            redirect_stderr.reset(new scoped_estream_redirect());
165    }
166
167    void exit() {
168        redirect_stdout.reset();
169        redirect_stderr.reset();
170    }
171};
172
173NAMESPACE_END(detail)
174
175/** \rst
176    This is a helper function to add a C++ redirect context manager to Python
177    instead of using a C++ guard. To use it, add the following to your binding code:
178
179    .. code-block:: cpp
180
181        #include <pybind11/iostream.h>
182
183        ...
184
185        py::add_ostream_redirect(m, "ostream_redirect");
186
187    You now have a Python context manager that redirects your output:
188
189    .. code-block:: python
190
191        with m.ostream_redirect():
192            m.print_to_cout_function()
193
194    This manager can optionally be told which streams to operate on:
195
196    .. code-block:: python
197
198        with m.ostream_redirect(stdout=true, stderr=true):
199            m.noisy_function_with_error_printing()
200
201 \endrst */
202inline class_<detail::OstreamRedirect> add_ostream_redirect(module m, std::string name = "ostream_redirect") {
203    return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
204        .def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
205        .def("__enter__", &detail::OstreamRedirect::enter)
206        .def("__exit__", [](detail::OstreamRedirect &self_, args) { self_.exit(); });
207}
208
209NAMESPACE_END(PYBIND11_NAMESPACE)
210