def __enter__(self):
assert self._original_fds is None, 'You can only use this object once'
# Save the original FDs and file objects.
# FIXME: How about stdin?
self._original_fds = [(fd, os.dup(fd)) for fd in (1, 2)]
self._old_stdout = sys.stdout
self._old_stderr = sys.stderr
# Redirect the Python file objects.
throwaway_fileno, self._redirected_path = tempfile.mkstemp()
# We need to reopen the file or Python and non-Python will have two different
# positions in the file (and we can't build a file object from a fileno).
os.close(throwaway_fileno)
self._redirected_file = open(self._redirected_path, 'w')
sys.stdout = self._redirected_file
sys.stderr = self._redirected_file
# Redirect the standard FDs.
os.dup2(self._redirected_file.fileno(), 1)
os.dup2(self._redirected_file.fileno(), 2)
return self
评论列表
文章目录