Skip to content

Commit

Permalink
Merge pull request #85 from minrk/check-sys-pipes
Browse files Browse the repository at this point in the history
sys_pipes: check that sys.stdout isn't being forwarded to itself
  • Loading branch information
minrk authored May 1, 2024
2 parents d7f3ed1 + 95cc9c9 commit 24cdb83
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
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

0 comments on commit 24cdb83

Please sign in to comment.