redirect_stdstream

pyscripts.redirect_stdstream(istream='stdout', ostream=None, stream_type='t')[source]

Redirect the information going to “istream” to the given stream.

Parameters:
  • istream (str) – where to redirect the output from. It can be any of “stdout” or “stderr”.
  • ostream (file) – object to collect the output stream.
  • stream_type (str) – type of stream. ‘b’ if it works with byte objects or ‘t’ if it does it with strings.
Returns:

output stream (io.StringIO by default).

Return type:

io.StringIO or file

Raises:

ValueError – if an incorrect input stream name or type is provided.

The call to this function opens a new context, so you can write:

>>> with redirect_stdstream() as out:
...     # Whatever is printed here will go to "out"
...     print('Hello')
...
>>> out.seek(0)
>>> captured = out.read()
>>> print(captured)
'Hello'

By default, it returns an io.StringIO object. If you are working with the logging package, beware that you might have to define a special logging.Logger instance for the messages sent within the duration of the context. For example, take a look at the following code:

>>> with pyscripts.redirect_stdstream('stdout') as stdout, pyscripts.redirect_stdstream('stderr') as stderr:
...     #
...     # Define the logger
...     #
...     logger = logging.getLogger('test')
...     logger.setLevel(logging.INFO)
...     #
...     # Define the handler for "stdout"
...     #
...     hi = logging.StreamHandler(stdout)
...     hi.setLevel(logging.INFO)
...     #
...     # Define the handler for "stderr"
...     #
...     he = logging.StreamHandler(stderr)
...     he.setLevel(logging.WARNING)
...     #
...     # Define the formatter
...     #
...     f = logging.Formatter('%(levelname)s: %(message)s')
...     hi.setFormatter(f)
...     he.setFormatter(f)
...     #
...     # Add handlers
...     #
...     logger.addHandler(hi)
...     logger.addHandler(he)
...     #
...     # Display some messages
...     #
...     logger.info('information')
...     logger.error('error')
...
>>> stdout.seek(0)
>>> stdout.readlines()
['INFO: information\n', 'ERROR: error\n']
>>> stderr.seek(0)
>>> stderr.readlines()
['ERROR: error\n']

Beware that the logging package uses strings. If a byte-like working object is passed to redirect_stdstream(), the execution will probably crash.

Warning

The call to this function will temporary close “sys.stdout” or “sys.stderr”, and will assign a new stream to them. Any object doing operations on the old streams will most likely cause an error.