3 A simple context manager for redirecting streams in Python.
4 The streams are redirected at the the C runtime level so that the output of C extensions
5 that use stdio will also be redirected.
7 null_file : a stream representing the null device (e.g. /dev/null on Unix)
8 redirect: a context manager for redirecting streams
10 Author: Baruch Sterin (sterin@berkeley.edu)
17 from contextlib
import contextmanager
19 null_file = open( os.devnull,
"w" )
23 fd = os.dup( f.fileno() )
32 fd = os.dup( src.fileno() )
36 with os.fdopen( fd,
"w", 0)
as f:
45 def redirect(dst = null_file, src = sys.stdout):
48 Redirect the src stream into dst.
51 with redirect( open("somefile.txt", sys.stdout ) ):
55 if src.fileno() == dst.fileno():
59 with
_dup( src )
as fd_dup_src:
64 os.close( src.fileno() )
65 os.dup2( dst.fileno(), src.fileno() )
70 os.close( src.fileno() )
71 os.dup2( fd_dup_src, src.fileno() )
76 Start redirection of src stream into dst. Return the duplicated file handle of the source.
79 fd = start_redirect( open("somefile.txt"), sys.stdout )
81 end_redirect(sys.stdout, fd)
84 if src.fileno() == dst.fileno():
87 fd_dup_src = os.dup( src.fileno() )
92 os.close( src.fileno() )
93 os.dup2( dst.fileno(), src.fileno() )
100 End redirection of stream src.Redirect the src stream into dst. src is the source stream and fd_dup_src is the value returned by
104 if fd_dup_src
is None:
108 os.close( src.fileno() )
109 os.dup2( fd_dup_src, src.fileno() )