Skip to content

Commit

Permalink
Merge pull request #38 from minrk/flush-on-exit
Browse files Browse the repository at this point in the history
  • Loading branch information
minrk committed Jul 6, 2020
2 parents b30ae5d + 2682eb4 commit d24f50c
Showing 1 changed file with 15 additions and 7 deletions.
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

0 comments on commit d24f50c

Please sign in to comment.