iostream.h 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /*
  2. pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
  3. Copyright (c) 2017 Henry F. Schreiner
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "pybind11.h"
  9. #include <streambuf>
  10. #include <ostream>
  11. #include <string>
  12. #include <memory>
  13. #include <iostream>
  14. NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  15. NAMESPACE_BEGIN(detail)
  16. // Buffer that writes to Python instead of C++
  17. class pythonbuf : public std::streambuf {
  18. private:
  19. using traits_type = std::streambuf::traits_type;
  20. char d_buffer[1024];
  21. object pywrite;
  22. object pyflush;
  23. int overflow(int c) {
  24. if (!traits_type::eq_int_type(c, traits_type::eof())) {
  25. *pptr() = traits_type::to_char_type(c);
  26. pbump(1);
  27. }
  28. return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
  29. }
  30. int sync() {
  31. if (pbase() != pptr()) {
  32. // This subtraction cannot be negative, so dropping the sign
  33. str line(pbase(), static_cast<size_t>(pptr() - pbase()));
  34. pywrite(line);
  35. pyflush();
  36. setp(pbase(), epptr());
  37. }
  38. return 0;
  39. }
  40. public:
  41. pythonbuf(object pyostream)
  42. : pywrite(pyostream.attr("write")),
  43. pyflush(pyostream.attr("flush")) {
  44. setp(d_buffer, d_buffer + sizeof(d_buffer) - 1);
  45. }
  46. /// Sync before destroy
  47. ~pythonbuf() {
  48. sync();
  49. }
  50. };
  51. NAMESPACE_END(detail)
  52. /** \rst
  53. This a move-only guard that redirects output.
  54. .. code-block:: cpp
  55. #include <pybind11/iostream.h>
  56. ...
  57. {
  58. py::scoped_ostream_redirect output;
  59. std::cout << "Hello, World!"; // Python stdout
  60. } // <-- return std::cout to normal
  61. You can explicitly pass the c++ stream and the python object,
  62. for example to guard stderr instead.
  63. .. code-block:: cpp
  64. {
  65. py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
  66. std::cerr << "Hello, World!";
  67. }
  68. \endrst */
  69. class scoped_ostream_redirect {
  70. protected:
  71. std::streambuf *old;
  72. std::ostream &costream;
  73. detail::pythonbuf buffer;
  74. public:
  75. scoped_ostream_redirect(
  76. std::ostream &costream = std::cout,
  77. object pyostream = module::import("sys").attr("stdout"))
  78. : costream(costream), buffer(pyostream) {
  79. old = costream.rdbuf(&buffer);
  80. }
  81. ~scoped_ostream_redirect() {
  82. costream.rdbuf(old);
  83. }
  84. scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
  85. scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
  86. scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
  87. scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
  88. };
  89. /** \rst
  90. Like `scoped_ostream_redirect`, but redirects cerr by default. This class
  91. is provided primary to make ``py::call_guard`` easier to make.
  92. .. code-block:: cpp
  93. m.def("noisy_func", &noisy_func,
  94. py::call_guard<scoped_ostream_redirect,
  95. scoped_estream_redirect>());
  96. \endrst */
  97. class scoped_estream_redirect : public scoped_ostream_redirect {
  98. public:
  99. scoped_estream_redirect(
  100. std::ostream &costream = std::cerr,
  101. object pyostream = module::import("sys").attr("stderr"))
  102. : scoped_ostream_redirect(costream,pyostream) {}
  103. };
  104. NAMESPACE_BEGIN(detail)
  105. // Class to redirect output as a context manager. C++ backend.
  106. class OstreamRedirect {
  107. bool do_stdout_;
  108. bool do_stderr_;
  109. std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
  110. std::unique_ptr<scoped_estream_redirect> redirect_stderr;
  111. public:
  112. OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
  113. : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
  114. void enter() {
  115. if (do_stdout_)
  116. redirect_stdout.reset(new scoped_ostream_redirect());
  117. if (do_stderr_)
  118. redirect_stderr.reset(new scoped_estream_redirect());
  119. }
  120. void exit() {
  121. redirect_stdout.reset();
  122. redirect_stderr.reset();
  123. }
  124. };
  125. NAMESPACE_END(detail)
  126. /** \rst
  127. This is a helper function to add a C++ redirect context manager to Python
  128. instead of using a C++ guard. To use it, add the following to your binding code:
  129. .. code-block:: cpp
  130. #include <pybind11/iostream.h>
  131. ...
  132. py::add_ostream_redirect(m, "ostream_redirect");
  133. You now have a Python context manager that redirects your output:
  134. .. code-block:: python
  135. with m.ostream_redirect():
  136. m.print_to_cout_function()
  137. This manager can optionally be told which streams to operate on:
  138. .. code-block:: python
  139. with m.ostream_redirect(stdout=true, stderr=true):
  140. m.noisy_function_with_error_printing()
  141. \endrst */
  142. inline class_<detail::OstreamRedirect> add_ostream_redirect(module m, std::string name = "ostream_redirect") {
  143. return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
  144. .def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
  145. .def("__enter__", &detail::OstreamRedirect::enter)
  146. .def("__exit__", [](detail::OstreamRedirect &self_, args) { self_.exit(); });
  147. }
  148. NAMESPACE_END(PYBIND11_NAMESPACE)