Skip to content

Instantly share code, notes, and snippets.

@russhughes
Created November 13, 2022 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russhughes/5afb0dca6e6b73d5c10d707334b06615 to your computer and use it in GitHub Desktop.
Save russhughes/5afb0dca6e6b73d5c10d707334b06615 to your computer and use it in GitHub Desktop.
Capture python output in a list
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