iostream.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. /*
  3. pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
  4. Copyright (c) 2017 Henry F. Schreiner
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. WARNING: The implementation in this file is NOT thread safe. Multiple
  8. threads writing to a redirected ostream concurrently cause data races
  9. and potentially buffer overflows. Therefore it is currently a requirement
  10. that all (possibly) concurrent redirected ostream writes are protected by
  11. a mutex.
  12. #HelpAppreciated: Work on iostream.h thread safety.
  13. For more background see the discussions under
  14. https://github.com/pybind/pybind11/pull/2982 and
  15. https://github.com/pybind/pybind11/pull/2995.
  16. */
  17. #pragma once
  18. #include "pybind11.h"
  19. #include <algorithm>
  20. #include <cstring>
  21. #include <iostream>
  22. #include <iterator>
  23. #include <memory>
  24. #include <ostream>
  25. #include <streambuf>
  26. #include <string>
  27. #include <utility>
  28. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  29. PYBIND11_NAMESPACE_BEGIN(detail)
  30. // Buffer that writes to Python instead of C++
  31. class pythonbuf : public std::streambuf {
  32. private:
  33. using traits_type = std::streambuf::traits_type;
  34. const size_t buf_size;
  35. std::unique_ptr<char[]> d_buffer;
  36. object pywrite;
  37. object pyflush;
  38. int overflow(int c) override {
  39. if (!traits_type::eq_int_type(c, traits_type::eof())) {
  40. *pptr() = traits_type::to_char_type(c);
  41. pbump(1);
  42. }
  43. return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
  44. }
  45. // Computes how many bytes at the end of the buffer are part of an
  46. // incomplete sequence of UTF-8 bytes.
  47. // Precondition: pbase() < pptr()
  48. size_t utf8_remainder() const {
  49. const auto rbase = std::reverse_iterator<char *>(pbase());
  50. const auto rpptr = std::reverse_iterator<char *>(pptr());
  51. auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };
  52. auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };
  53. auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };
  54. auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };
  55. // If the last character is ASCII, there are no incomplete code points
  56. if (is_ascii(*rpptr)) {
  57. return 0;
  58. }
  59. // Otherwise, work back from the end of the buffer and find the first
  60. // UTF-8 leading byte
  61. const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;
  62. const auto leading = std::find_if(rpptr, rpend, is_leading);
  63. if (leading == rbase) {
  64. return 0;
  65. }
  66. const auto dist = static_cast<size_t>(leading - rpptr);
  67. size_t remainder = 0;
  68. if (dist == 0) {
  69. remainder = 1; // 1-byte code point is impossible
  70. } else if (dist == 1) {
  71. remainder = is_leading_2b(*leading) ? 0 : dist + 1;
  72. } else if (dist == 2) {
  73. remainder = is_leading_3b(*leading) ? 0 : dist + 1;
  74. }
  75. // else if (dist >= 3), at least 4 bytes before encountering an UTF-8
  76. // leading byte, either no remainder or invalid UTF-8.
  77. // Invalid UTF-8 will cause an exception later when converting
  78. // to a Python string, so that's not handled here.
  79. return remainder;
  80. }
  81. // This function must be non-virtual to be called in a destructor.
  82. int _sync() {
  83. if (pbase() != pptr()) { // If buffer is not empty
  84. gil_scoped_acquire tmp;
  85. // This subtraction cannot be negative, so dropping the sign.
  86. auto size = static_cast<size_t>(pptr() - pbase());
  87. size_t remainder = utf8_remainder();
  88. if (size > remainder) {
  89. str line(pbase(), size - remainder);
  90. pywrite(std::move(line));
  91. pyflush();
  92. }
  93. // Copy the remainder at the end of the buffer to the beginning:
  94. if (remainder > 0) {
  95. std::memmove(pbase(), pptr() - remainder, remainder);
  96. }
  97. setp(pbase(), epptr());
  98. pbump(static_cast<int>(remainder));
  99. }
  100. return 0;
  101. }
  102. int sync() override { return _sync(); }
  103. public:
  104. explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024)
  105. : buf_size(buffer_size), d_buffer(new char[buf_size]), pywrite(pyostream.attr("write")),
  106. pyflush(pyostream.attr("flush")) {
  107. setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
  108. }
  109. pythonbuf(pythonbuf &&) = default;
  110. /// Sync before destroy
  111. ~pythonbuf() override { _sync(); }
  112. };
  113. PYBIND11_NAMESPACE_END(detail)
  114. /** \rst
  115. This a move-only guard that redirects output.
  116. .. code-block:: cpp
  117. #include <pybind11/iostream.h>
  118. ...
  119. {
  120. py::scoped_ostream_redirect output;
  121. std::cout << "Hello, World!"; // Python stdout
  122. } // <-- return std::cout to normal
  123. You can explicitly pass the c++ stream and the python object,
  124. for example to guard stderr instead.
  125. .. code-block:: cpp
  126. {
  127. py::scoped_ostream_redirect output{
  128. std::cerr, py::module::import("sys").attr("stderr")};
  129. std::cout << "Hello, World!";
  130. }
  131. \endrst */
  132. class scoped_ostream_redirect {
  133. protected:
  134. std::streambuf *old;
  135. std::ostream &costream;
  136. detail::pythonbuf buffer;
  137. public:
  138. explicit scoped_ostream_redirect(std::ostream &costream = std::cout,
  139. const object &pyostream
  140. = module_::import("sys").attr("stdout"))
  141. : costream(costream), buffer(pyostream) {
  142. old = costream.rdbuf(&buffer);
  143. }
  144. ~scoped_ostream_redirect() { costream.rdbuf(old); }
  145. scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
  146. scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
  147. scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
  148. scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
  149. };
  150. /** \rst
  151. Like `scoped_ostream_redirect`, but redirects cerr by default. This class
  152. is provided primary to make ``py::call_guard`` easier to make.
  153. .. code-block:: cpp
  154. m.def("noisy_func", &noisy_func,
  155. py::call_guard<scoped_ostream_redirect,
  156. scoped_estream_redirect>());
  157. \endrst */
  158. class scoped_estream_redirect : public scoped_ostream_redirect {
  159. public:
  160. explicit scoped_estream_redirect(std::ostream &costream = std::cerr,
  161. const object &pyostream
  162. = module_::import("sys").attr("stderr"))
  163. : scoped_ostream_redirect(costream, pyostream) {}
  164. };
  165. PYBIND11_NAMESPACE_BEGIN(detail)
  166. // Class to redirect output as a context manager. C++ backend.
  167. class OstreamRedirect {
  168. bool do_stdout_;
  169. bool do_stderr_;
  170. std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
  171. std::unique_ptr<scoped_estream_redirect> redirect_stderr;
  172. public:
  173. explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
  174. : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
  175. void enter() {
  176. if (do_stdout_) {
  177. redirect_stdout.reset(new scoped_ostream_redirect());
  178. }
  179. if (do_stderr_) {
  180. redirect_stderr.reset(new scoped_estream_redirect());
  181. }
  182. }
  183. void exit() {
  184. redirect_stdout.reset();
  185. redirect_stderr.reset();
  186. }
  187. };
  188. PYBIND11_NAMESPACE_END(detail)
  189. /** \rst
  190. This is a helper function to add a C++ redirect context manager to Python
  191. instead of using a C++ guard. To use it, add the following to your binding code:
  192. .. code-block:: cpp
  193. #include <pybind11/iostream.h>
  194. ...
  195. py::add_ostream_redirect(m, "ostream_redirect");
  196. You now have a Python context manager that redirects your output:
  197. .. code-block:: python
  198. with m.ostream_redirect():
  199. m.print_to_cout_function()
  200. This manager can optionally be told which streams to operate on:
  201. .. code-block:: python
  202. with m.ostream_redirect(stdout=true, stderr=true):
  203. m.noisy_function_with_error_printing()
  204. \endrst */
  205. inline class_<detail::OstreamRedirect>
  206. add_ostream_redirect(module_ m, const std::string &name = "ostream_redirect") {
  207. return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local())
  208. .def(init<bool, bool>(), arg("stdout") = true, arg("stderr") = true)
  209. .def("__enter__", &detail::OstreamRedirect::enter)
  210. .def("__exit__", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); });
  211. }
  212. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  213. #else
  214. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  215. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)