title: How to escape from the standard output redirection in Python
body: <p>I want to process a live output of a thirdparty script, printing some lines that match a pattern but skipping others:</p>
  
  <pre><code>def thirdparty_code():
      from random import choice
      stuff = ['keep: important stuff', 'ignore: boring stuff']
      while True:
          chosen_line = choice(stuff)
          print(chosen_line)
  </code></pre>
  
  <p>I use <code>redirect_stdout</code> (which passes lines to my dummy IO) and an extended <code>StringIO</code> (which serves as the IO but also calls my filtering function). However, when I call <code>print()</code> inside of my processing function I get a <code>RecursionError</code> - which is not unexpected:</p>
  
  <pre><code>from io import StringIO
  from contextlib import redirect_stdout
  
  class StringIOWithCallback(StringIO):
  
      def __init__(self, callback, **kwargs):
          super().__init__(**kwargs)
          self.callback = callback
  
      def write(self, s):
          super().write(s)
          self.callback(s)
  
  def filter_boring_stuff_out(line):
      if line.startswith('ignore'):
          return
      print(line)
  
  my_io = StringIOWithCallback(filter_boring_stuff_out)
  
  with redirect_stdout(my_io):
      thirdparty_code()
  </code></pre>
  
  <p>I wonder if it is possible to escape from the redirect, e.g. specifying the <code>file</code> parameter in <code>print()</code> function so that it prints to the actual standard output. I know that I can easily use the standard error stream:</p>
  
  <pre><code>import sys
  print(line, file=sys.stderr)
  </code></pre>
  
  <p>But I specifically want to use the standard output. Is there a nice, pythonic way to do that?</p>