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

avoid unnecessary close of original FDs #11

Merged
merged 1 commit into from
Jan 22, 2018
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
26 changes: 25 additions & 1 deletion test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
from __future__ import print_function

import io
import os
from tempfile import TemporaryFile
import time

import mock

from wurlitzer import (
Expand Down Expand Up @@ -73,7 +76,7 @@ def test_sys_pipes():
with mock.patch('sys.stdout', stdout), mock.patch('sys.stderr', stderr), sys_pipes():
printf(u"Hellø")
printf_err(u"Hi, stdérr")

assert stdout.getvalue() == u"Hellø\n"
assert stderr.getvalue() == u"Hi, stdérr\n"

Expand All @@ -89,3 +92,24 @@ def test_redirect_everything():
assert stderr.getvalue() == u"Hi, stdérr\n"


def count_fds():
"""utility for counting file descriptors"""
proc_fds = '/proc/{}/fd'.format(os.getpid())
if os.path.isdir(proc_fds):
return len(proc_fds)
else:
# this is an approximate count,
# but it should at least be stable if we aren't leaking
with TemporaryFile() as tf:
return tf.fileno()


def test_fd_leak():
base_count = count_fds()
with pipes():
print('ok')
assert count_fds() == base_count
for i in range(10):
with pipes():
print('ok')
assert count_fds() == base_count
12 changes: 5 additions & 7 deletions wurlitzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def forwarder():
self.thread = threading.Thread(target=forwarder)
self.thread.daemon = True
self.thread.start()

return self.handle

def __exit__(self, exc_type, exc_value, traceback):
Expand All @@ -202,9 +202,7 @@ def __exit__(self, exc_type, exc_value, traceback):
os.write(self._control_w, b'\1')
self.thread.join()
os.close(self._control_w)
for real_fd in self._real_fds.values():
os.close(real_fd)


# restore original state
for name, real_fd in self._real_fds.items():
save_fd = self._save_fds[name]
Expand All @@ -217,12 +215,12 @@ def __exit__(self, exc_type, exc_value, traceback):
@contextmanager
def pipes(stdout=PIPE, stderr=PIPE, encoding=_default_encoding):
"""Capture C-level stdout/stderr in a context manager.

The return value for the context manager is (stdout, stderr).

Examples
--------

>>> with capture() as (stdout, stderr):
... printf("C-level stdout")
... output = stdout.read()
Expand Down