Skip to content

Commit

Permalink
Don't capture passthrough runs when file handler given (#25)
Browse files Browse the repository at this point in the history
Co-authored-by: Zoran Simic <zsimic@netflix.com>
  • Loading branch information
zsimic and Zoran Simic committed Dec 13, 2023
1 parent 3a15349 commit c614471
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
18 changes: 14 additions & 4 deletions src/runez/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,15 +624,19 @@ def _run_popen(args, popen_args, passthrough, fatal, stdout, stderr):
# Capture output, but also let it pass-through as-is to the terminal
stdout_r, stdout_w = pty.openpty()
stderr_r, stderr_w = pty.openpty()
stdout_buffer = BytesIO()
stderr_buffer = BytesIO()
term_size = struct.pack("HHHH", SYS_INFO.terminal.lines, SYS_INFO.terminal.columns, 0, 0)
for fd in (stdout_r, stdout_w, stderr_r, stderr_w):
fcntl.ioctl(fd, termios.TIOCSWINSZ, term_size)

passthrough = getattr(passthrough, "stream", passthrough) # Convenience support for things like logging handlers
if not hasattr(passthrough, "write"):
if hasattr(passthrough, "write"):
# Don't accumulate out to RAM if we're passing it through to a file
stdout_buffer = stderr_buffer = None

else:
passthrough = None
stdout_buffer = BytesIO()
stderr_buffer = BytesIO()

with subprocess.Popen(args, stdout=stdout_w, stderr=stderr_w, **popen_args) as p: # nosec
os.close(stdout_w)
Expand Down Expand Up @@ -666,7 +670,13 @@ def _run_popen(args, popen_args, passthrough, fatal, stdout, stderr):
sys.stderr.flush()
os.close(stdout_r)
os.close(stderr_r)
return p, uncolored(decode(stdout_buffer.getvalue())), uncolored(decode(stderr_buffer.getvalue()))
if stdout_buffer:
stdout_buffer = uncolored(decode(stdout_buffer.getvalue()))

if stderr_buffer:
stderr_buffer = uncolored(decode(stderr_buffer.getvalue()))

return p, stdout_buffer, stderr_buffer


def _safe_write(target, data, flush=None):
Expand Down
7 changes: 6 additions & 1 deletion tests/test_program.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,13 @@ def test_capture(monkeypatch):
assert "chatter hello" in logged.pop()
assert runez.run(CHATTER, stdout=None) == RunResult(None, "", 0)
assert "Running:" in logged.pop()

r = runez.run(CHATTER, "hello", fatal=True, passthrough=True)
assert r == RunResult("hello", "", 0)

crasher = CrashingWrite()
assert runez.run(CHATTER, "hello", fatal=True, passthrough=crasher) == RunResult("hello", "", 0)
r = runez.run(CHATTER, "hello", fatal=True, passthrough=crasher)
assert r == RunResult(None, None, 0)
assert crasher.crash_counter
assert "hello" in logged.pop()

Expand Down

0 comments on commit c614471

Please sign in to comment.