Skip to content

flush sys streams on enter/exit #38

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

Merged
merged 2 commits into from
Jul 6, 2020
Merged
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
22 changes: 15 additions & 7 deletions wurlitzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,19 @@ def _finish_handle(self):
"""Finish handle, if anything should be done when it's all wrapped up."""
pass

def __enter__(self):
# flush anything out before starting
def _flush(self):
"""flush sys.stdout/err and low-level FDs"""
if self._stdout and sys.stdout:
sys.stdout.flush()
if self._stderr and sys.stderr:
sys.stderr.flush()

libc.fflush(c_stdout_p)
libc.fflush(c_stderr_p)

def __enter__(self):
# flush anything out before starting
self._flush()
# setup handle
self._setup_handle()
self._control_r, self._control_w = os.pipe()
Expand All @@ -172,8 +181,7 @@ def flush_main():
msg = flush_queue.get()
if msg == 'stop':
return
libc.fflush(c_stdout_p)
libc.fflush(c_stderr_p)
self._flush()

flush_thread = threading.Thread(target=flush_main)
flush_thread.daemon = True
Expand Down Expand Up @@ -241,9 +249,9 @@ def forwarder():
return self.handle

def __exit__(self, exc_type, exc_value, traceback):
# flush the underlying C buffers
libc.fflush(c_stdout_p)
libc.fflush(c_stderr_p)
# flush before exiting
self._flush()

# signal output is complete on control pipe
os.write(self._control_w, b'\1')
self.thread.join()
Expand Down