|
4 | 4 | from collections import deque |
5 | 5 | from functools import wraps |
6 | 6 |
|
7 | | -__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack", "ignored"] |
| 7 | +__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack", |
| 8 | + "ignored", "redirect_stdout"] |
8 | 9 |
|
9 | 10 |
|
10 | 11 | class ContextDecorator(object): |
@@ -140,6 +141,43 @@ def __enter__(self): |
140 | 141 | def __exit__(self, *exc_info): |
141 | 142 | self.thing.close() |
142 | 143 |
|
| 144 | +class redirect_stdout: |
| 145 | + """Context manager for temporarily redirecting stdout to another file |
| 146 | +
|
| 147 | + # How to send help() to stderr |
| 148 | +
|
| 149 | + with redirect_stdout(sys.stderr): |
| 150 | + help(dir) |
| 151 | +
|
| 152 | + # How to write help() to a file |
| 153 | +
|
| 154 | + with open('help.txt', 'w') as f: |
| 155 | + with redirect_stdout(f): |
| 156 | + help(pow) |
| 157 | +
|
| 158 | + # How to capture disassembly to a string |
| 159 | +
|
| 160 | + import dis |
| 161 | + import io |
| 162 | +
|
| 163 | + f = io.StringIO() |
| 164 | + with redirect_stdout(f): |
| 165 | + dis.dis('x**2 - y**2') |
| 166 | + s = f.getvalue() |
| 167 | +
|
| 168 | + """ |
| 169 | + |
| 170 | + def __init__(self, new_target): |
| 171 | + self.new_target = new_target |
| 172 | + |
| 173 | + def __enter__(self): |
| 174 | + self.old_target = sys.stdout |
| 175 | + sys.stdout = self.new_target |
| 176 | + return self.new_target |
| 177 | + |
| 178 | + def __exit__(self, exctype, excinst, exctb): |
| 179 | + sys.stdout = self.old_target |
| 180 | + |
143 | 181 | @contextmanager |
144 | 182 | def ignored(*exceptions): |
145 | 183 | """Context manager to ignore specified exceptions |
|
0 commit comments