Capturing Standard Output in Python
In Python, it's often useful to capture the output printed to the standard output (stdout) for various reasons, such as saving it for later processing or testing. One common scenario involves calling a function from a library, such as do_something(my_object), that prints information to stdout.
To capture the output of this function call, the following approach can be used:
Implement a Concatenating Context Manager (Capturing):
Use the Context Manager:
Obtain the Captured Output:
Example Usage:
<code class="python">from contextlib import redirect_stdout # redirect_stdout is only available in Python 3.4 or later def do_something(my_object): print('stdout info') with redirect_stdout(StringIO()) as stdout: do_something(my_object) captured_output = stdout.getvalue()</code>
Using the Python 3.4 syntax:
<code class="python">with StringIO() as output: with redirect_stdout(output): do_something(my_object) captured_output = output.getvalue()</code>
By following these steps, you can easily capture the stdout output from a Python function call, enabling you to utilize the printed information for further processing, debugging, or testing purposes.
The above is the detailed content of How to Capture Standard Output in Python?. For more information, please follow other related articles on the PHP Chinese website!