def _redirected_fd(to=os.devnull, stdio=None):
if stdio is None:
stdio = sys.stdout
stdio_fd = _get_fileno(stdio)
# copy stdio_fd before it is overwritten
# NOTE: `copied` is inheritable on Windows when duplicating a standard
# stream
with os.fdopen(os.dup(stdio_fd), 'wb') as copied:
stdio.flush() # flush library buffers that dup2 knows nothing about
try:
os.dup2(_get_fileno(to), stdio_fd) # $ exec >&to
except ValueError: # filename
with open(to, 'wb') as to_file:
os.dup2(to_file.fileno(), stdio_fd) # $ exec > to
try:
yield stdio # allow code to be run with the redirected stdio
finally:
# restore stdio to its previous value
# NOTE: dup2 makes stdio_fd inheritable unconditionally
stdio.flush()
os.dup2(copied.fileno(), stdio_fd) # $ exec >&copied
评论列表
文章目录