redirect_stdstream¶
-
pyscripts.redirect_stdstream(istream='stdout', ostream=None, stream_type='t')[source]¶ Redirect the information going to “istream” to the given stream.
Parameters: Returns: output stream (
io.StringIOby 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.StringIOobject. If you are working with theloggingpackage, beware that you might have to define a speciallogging.Loggerinstance 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
loggingpackage uses strings. If a byte-like working object is passed toredirect_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.