Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sys_pipes: check that sys.stdout isn't being forwarded to itself #85

Merged
merged 1 commit into from
May 1, 2024
Merged
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
10 changes: 10 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ def test_sys_pipes():
assert stderr.getvalue() == u"Hi, stdérr\n"


def test_sys_pipes_check():
# pytest redirects stdout; un-redirect it for the test
with mock.patch('sys.stdout', sys.__stdout__), mock.patch(
'sys.stderr', sys.__stderr__
):
with pytest.raises(ValueError):
with sys_pipes():
pass


def test_redirect_everything():
stdout = io.StringIO()
stderr = io.StringIO()
Expand Down
21 changes: 20 additions & 1 deletion wurlitzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,10 +532,29 @@ def __exit__(self, *exc_info):
def sys_pipes(encoding=_default_encoding, bufsize=None):
"""Redirect C-level stdout/stderr to sys.stdout/stderr

This is useful of sys.sdout/stderr are already being forwarded somewhere.
This is useful of sys.sdout/stderr are already being forwarded somewhere,
e.g. in a Jupyter kernel.

DO NOT USE THIS if sys.stdout and sys.stderr are not already being forwarded.
"""
# check that we aren't forwarding stdout to itself
for name in ("stdout", "stderr"):
stream = getattr(sys, name)
capture_stream = getattr(sys, "__{}__".format(name))
try:
fd = stream.fileno()
capture_fd = capture_stream.fileno()
except Exception:
# ignore errors - if sys.stdout doesn't need a fileno,
# it's definitely not the original sys.__stdout__
continue
else:
if fd == capture_fd:
raise ValueError(
"Cannot forward sys.__{0}__ to sys.{0}: they are the same! Maybe you want wurlitzer.pipes()?".format(
name
)
)
return pipes(sys.stdout, sys.stderr, encoding=encoding, bufsize=bufsize)


Expand Down
Loading