abc-master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
redirect.py
Go to the documentation of this file.
1 """
2 
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.
6 
7 null_file : a stream representing the null device (e.g. /dev/null on Unix)
8 redirect: a context manager for redirecting streams
9 
10 Author: Baruch Sterin (sterin@berkeley.edu)
11 
12 """
13 
14 import os
15 import sys
16 
17 from contextlib import contextmanager
18 
19 null_file = open( os.devnull, "w" )
20 
21 @contextmanager
22 def _dup( f ):
23  fd = os.dup( f.fileno() )
24  yield fd
25  os.close(fd)
26 
27 @contextmanager
28 def save_stdout( src = sys.stdout ):
29  """
30  Redirect
31  """
32  fd = os.dup( src.fileno() )
33  own = True
34 
35  try:
36  with os.fdopen( fd, "w", 0) as f:
37  own = False
38  yield f
39  except:
40  if own:
41  os.close(fd)
42  raise
43 
44 @contextmanager
45 def redirect(dst = null_file, src = sys.stdout):
46 
47  """
48  Redirect the src stream into dst.
49 
50  Example:
51  with redirect( open("somefile.txt", sys.stdout ) ):
52  do some stuff ...
53  """
54 
55  if src.fileno() == dst.fileno():
56  yield
57  return
58 
59  with _dup( src ) as fd_dup_src:
60 
61  dst.flush()
62 
63  src.flush()
64  os.close( src.fileno() )
65  os.dup2( dst.fileno(), src.fileno() )
66 
67  yield
68 
69  src.flush()
70  os.close( src.fileno() )
71  os.dup2( fd_dup_src, src.fileno() )
72 
73 def start_redirect(dst = null_file, src = sys.stdout):
74 
75  """
76  Start redirection of src stream into dst. Return the duplicated file handle of the source.
77 
78  Example:
79  fd = start_redirect( open("somefile.txt"), sys.stdout )
80  ... do some stuff ...
81  end_redirect(sys.stdout, fd)
82  """
83 
84  if src.fileno() == dst.fileno():
85  return None
86 
87  fd_dup_src = os.dup( src.fileno() )
88 
89  dst.flush()
90  src.flush()
91 
92  os.close( src.fileno() )
93  os.dup2( dst.fileno(), src.fileno() )
94 
95  return fd_dup_src
96 
97 def end_redirect(src, fd_dup_src):
98 
99  """
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
101  start_redirect()
102  """
103 
104  if fd_dup_src is None:
105  return
106 
107  src.flush()
108  os.close( src.fileno() )
109  os.dup2( fd_dup_src, src.fileno() )
110 
111  os.close(fd_dup_src)
def _dup
Definition: redirect.py:22
def end_redirect
Definition: redirect.py:97
def save_stdout
Definition: redirect.py:28
def redirect
Definition: redirect.py:45
def start_redirect
Definition: redirect.py:73