This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author rhettinger
Recipients rhettinger
Date 2012-08-29.04:26:23
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
The technique of temporarily redirecting stdout could be encapsulated in a context manager.

print('This goes to stdout')
with RedirectStdout(sys.stderr):
     print('This goes to stderr')
     print('So does this')
print('This goes to stdout')

The print function already supports redirection but it much be done for every single call to print().  The context manager let's the redirection apply to a batch of statements.

The context manager is also useful with existing tools that don't currently provide output redirection hooks:

   from collections import namedtuple
   with open('', 'w') as module:
       with RedirectStdout(module):
            namedtuple('Person', ['name', 'age', 'email'], verbose=True)

   import dis
   with open('disassembly.txt', 'w') as f:
       with RedirectStdout(f):

A possible implementation is:

class RedirectStdout:
    ''' Create a context manager for redirecting sys.stdout
        to another file.
    def __init__(self, new_target):
        self.new_target = new_target

    def __enter__(self):
        self.old_target = sys.stdout
        sys.stdout = self.new_target
        return self

    def __exit__(self, exctype, excinst, exctb):
        sys.stdout = self.old_target
Date User Action Args
2012-08-29 04:26:24rhettingersetrecipients: + rhettinger
2012-08-29 04:26:24rhettingersetmessageid: <>
2012-08-29 04:26:23rhettingerlinkissue15805 messages
2012-08-29 04:26:23rhettingercreate