Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python catch print

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 :: numpy.where 
Python :: num2words python 
Python :: take columns to rows in pandas 
Python :: python count appearances in list 
Python :: lower method in python 
Python :: logger 
Python :: i++ in python 
Python :: make Python class serializable 
Python :: python get file ending 
Python :: purpose of migration folder in django 
Python :: pytest fixture 
Python :: join multiple excel files with python 
Python :: how to normalize scipy cross correlation 
Python :: check if a value is in index pandas dataframe 
Python :: install web3 on python 
Python :: how to convert string to int in python 
Python :: python script to write dataframe on excel 
Python :: how to sort numpy array 
Python :: cosine similarity numpy 
Python :: Use operator in python list 
Python :: frequency meaning 
Python :: datetime to string 
Python :: Python NumPy ravel function Syntax 
Python :: django model 
Python :: has no attribute pythin 
Python :: Multiple list comprehension 
Python :: python how to print 
Python :: how to use str() 
Python :: csv to excel python 
Python :: pass in python 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =