Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions include/pybind11/iostream.h
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,18 @@ class scoped_ostream_redirect {
old = costream.rdbuf(&buffer);
}

~scoped_ostream_redirect() { costream.rdbuf(old); }
~scoped_ostream_redirect() {
if (old) {
costream.rdbuf(old);
}
}

scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
scoped_ostream_redirect(scoped_ostream_redirect &&other) noexcept
: old(other.old), costream(other.costream), buffer(std::move(other.buffer)) {
other.old = nullptr; // Disarm moved-from destructor
costream.rdbuf(&buffer); // Re-point stream to our buffer
}
scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
};
Expand Down
7 changes: 7 additions & 0 deletions tests/test_iostream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,11 @@ TEST_SUBMODULE(iostream, m) {
.def("stop", &TestThread::stop)
.def("join", &TestThread::join)
.def("sleep", &TestThread::sleep);

m.def("move_redirect_output", [](const std::string &msg) {
py::scoped_ostream_redirect redir1(std::cout, py::module_::import("sys").attr("stdout"));
std::cout << "before" << std::flush;
py::scoped_ostream_redirect redir2(std::move(redir1));
std::cout << msg << std::flush;
});
}
7 changes: 7 additions & 0 deletions tests/test_iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,13 @@ def test_redirect_both(capfd):
assert stream2.getvalue() == msg2


def test_move_redirect(capsys):
m.move_redirect_output("after")
stdout, stderr = capsys.readouterr()
assert stdout == "beforeafter"
assert not stderr


@pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads")
def test_threading():
with m.ostream_redirect(stdout=True, stderr=False):
Expand Down
Loading