Home > Backend Development > Python Tutorial > How to Capture Standard Output from Python Function Calls?

How to Capture Standard Output from Python Function Calls?

Susan Sarandon
Release: 2024-11-03 13:20:03
Original
707 people have browsed it

How to Capture Standard Output from Python Function Calls?

Capturing Standard Output from Python Function Calls

When using Python libraries that modify objects and print statistics to stdout, there may be a need to capture this output for further analysis. However, directly modifying the function to return such information might not always be feasible.

To address this, one can utilize the Capturing context manager:

<code class="python">from io import StringIO
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio  # free up some memory
        sys.stdout = self._stdout</code>
Copy after login

The Capturing context manager can be used as follows:

<code class="python">with Capturing() as output:
    do_something(my_object)</code>
Copy after login

After the function call, the output list will contain the lines printed by the function.

This technique can be applied multiple times, and the results can be concatenated:

<code class="python">with Capturing() as output:
    print('hello world')

print('displays on screen')

with Capturing(output) as output:  # note the constructor argument
    print('hello world2')

print('done')
print('output:', output)</code>
Copy after login

Output:

displays on screen
done
output: ['hello world', 'hello world2']
Copy after login

This approach provides an effective workaround for capturing stdout output when it is not possible to modify the do_something() function directly.

The above is the detailed content of How to Capture Standard Output from Python Function Calls?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template