Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python capture stdout

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
        
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)
Comment

PREVIOUS NEXT
Code Example
Python :: Async-Sync 
Python :: python order number list 
Python :: push button raspberry pi 
Python :: negative slicing in python list 
Python :: loop through files in a directory python 
Python :: convert string to int python 
Python :: command for python shell 
Python :: Sendgrid dynamic templating 
Python :: changes in settings.py for media storage without db 
Python :: Python NumPy expand_dims Function Example 
Python :: giving number of letter in python 
Python :: Python DateTime Date Class Syntax 
Python :: space complexity python 
Python :: python increment by 1 
Python :: python list equality 
Python :: roc curve 
Python :: extend python 
Python :: comentar codigo en python 
Python :: python : a counter 
Python :: python map 
Python :: merge list elements python 
Python :: numpy datatime object 
Python :: python language 
Python :: polls/models.py 
Python :: Remove an element from a Python list Using pop() method 
Python :: f string 
Python :: densenet python keras 
Python :: comment all selected lines in python 
Python :: python 3.8 release date 
Python :: python size of list 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =