Created
November 13, 2022 17:03
-
-
Save russhughes/5afb0dca6e6b73d5c10d707334b06615 to your computer and use it in GitHub Desktop.
Capture python output in a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from io import StringIO | |
def print_function() : | |
print( "Hello") | |
print ( "World") | |
print ( "New\nLine") | |
class Capturing(list): | |
def __enter__(self): | |
self._stdout = sys.stdout | |
sys.stdout = StringIO() | |
self._current_string = sys.stdout | |
return self | |
def __exit__(self, *args): | |
self.extend(self._current_string.getvalue().splitlines()) | |
del self._current_string | |
sys.stdout = self._stdout | |
with Capturing() as output: | |
print_function() | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment