title: How to run Python subprocess and stream but also filter stdout and stderr?
body: <p>I have a server-like app I want to run from Python. It never stops until user interrupts it. I want to continuously redirect both stdout and stderr to parent when the app runs. Lucklily, that's exactly what <code>subprocess.run</code> does.</p>
  
  <p>Shell:</p>
  
  <pre><code>$ my-app
  1
  2
  3
  ...
  </code></pre>
  
  <p><code>wrapper.py</code>:</p>
  
  <pre><code>import subprocess
  subprocess.run(['my-app'])
  </code></pre>
  
  <p>Executing <code>wrapper.py</code>:</p>
  
  <pre><code>$ python wrapper.py
  1
  2
  3
  ...
  </code></pre>
  
  <p>I believe it's thanks to the fact that <code>subprocess.run</code> inherits stdout and stderr file descriptiors from the parent process. Good.</p>
  
  <p>But now I need to do something when the app outputs particular line. Imagine I want to run arbitrary Python code when the output line will contain <code>4</code>:</p>
  
  <pre><code>$ python wrapper.py
  1
  2
  3
  4   &lt;-- here I want to do something
  ...
  </code></pre>
  
  <p>Or I want to remove some lines from the output:</p>
  
  <pre><code>$ python wrapper.py   &lt;-- allowed only odd numbers
  1
  3
  ...
  </code></pre>
  
  <p>I thought I could have a filtering function which I'll just hook somehow into the <code>subprocess.run</code> and it will get called with every line of the output, regardless whether it's stdout or stderr:</p>
  
  <pre><code>def filter_fn(line):
      if line ...:
          return line.replace(...
      ...
  </code></pre>
  
  <p>But how to achieve this? How to hook such or similar function into the <code>subprocess.run</code> call?</p>
  
  <hr>
  
  <p><strong>Note:</strong> I can't use the <a href="https://pypi.python.org/pypi/sh" rel="nofollow"><code>sh</code></a> library as it has zero support for Windows.</p>