@contextlib.contextmanager
def redirect_fd(fd):
 save = os.dup(fd)
 (r, w) = os.pipe()
 try:
  os.dup2(w, fd)
  (yield io.open(r, 'r'))
 finally:
  os.close(w)
  os.dup2(save, fd)
  os.close(save)

@ contextlib . contextmanager def redirect_fd ( fd ) : save = os . dup ( fd ) ( r , w ) = os . pipe ( ) try : os . dup2 ( w , fd ) ( yield io . open ( r , 'r' ) ) finally : os . close ( w ) os . dup2 ( save , fd ) os . close ( save )
temporarily redirect *fd* to a pipes write end and return a file object wrapping the pipes read end .