Capture standard output. Use this context manager to capture print statements and other output sent to standard output. Examples: ```python with mo.capture_stdout() as buffer: print("Hello!") output = buffer.getvalue() ```
()
| 20 | |
| 21 | @contextlib.contextmanager |
| 22 | def capture_stdout() -> Iterator[io.StringIO]: |
| 23 | """Capture standard output. |
| 24 | |
| 25 | Use this context manager to capture print statements and |
| 26 | other output sent to standard output. |
| 27 | |
| 28 | Examples: |
| 29 | ```python |
| 30 | with mo.capture_stdout() as buffer: |
| 31 | print("Hello!") |
| 32 | output = buffer.getvalue() |
| 33 | ``` |
| 34 | """ |
| 35 | proxy = sys.stdout |
| 36 | if _is_proxy(proxy): |
| 37 | # Temporarily swap the thread-local stream to a StringIO so that |
| 38 | # writes from this thread are captured while other threads are |
| 39 | # unaffected. |
| 40 | buffer = io.StringIO() |
| 41 | old = proxy._get_stream() # type: ignore[union-attr] |
| 42 | proxy._set_stream(buffer) # type: ignore[union-attr] |
| 43 | try: |
| 44 | yield buffer |
| 45 | finally: |
| 46 | proxy._set_stream(old) # type: ignore[union-attr] |
| 47 | else: |
| 48 | with contextlib.redirect_stdout(io.StringIO()) as buffer: |
| 49 | yield buffer |
| 50 | |
| 51 | |
| 52 | @contextlib.contextmanager |
searching dependent graphs…