Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily Redirect stdout/stderr

Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)?

Edit:

The problem with the current solutions (which I at first remembered but then forgot) is that they don't redirect; rather, they just replace the streams in their entirety. Hence, if a method has a local copy of one the variable for any reason (e.g. because the stream was passed as a parameter to something), it won't work.

Any solutions?

like image 732
user541686 Avatar asked Jul 22 '11 21:07

user541686


People also ask

How do I redirect STDERR and stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.

How can I redirect stdout and STDERR in same location?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.


1 Answers

You can also put the redirection logic in a contextmanager.

import os import sys  class RedirectStdStreams(object):     def __init__(self, stdout=None, stderr=None):         self._stdout = stdout or sys.stdout         self._stderr = stderr or sys.stderr      def __enter__(self):         self.old_stdout, self.old_stderr = sys.stdout, sys.stderr         self.old_stdout.flush(); self.old_stderr.flush()         sys.stdout, sys.stderr = self._stdout, self._stderr      def __exit__(self, exc_type, exc_value, traceback):         self._stdout.flush(); self._stderr.flush()         sys.stdout = self.old_stdout         sys.stderr = self.old_stderr  if __name__ == '__main__':      devnull = open(os.devnull, 'w')     print('Fubar')      with RedirectStdStreams(stdout=devnull, stderr=devnull):         print("You'll never see me")      print("I'm back!") 
like image 166
Rob Cowie Avatar answered Sep 23 '22 07:09

Rob Cowie