How can I redirect only part of a stream?
<p>I'm using Python on bash on Linux. I would like to be able to suppress error messages from a particular module, but keep other error messages. An example would probably be the most efficient way to convey what I want:</p>

<hr>

<h3>File: <code>module.py</code></h3>

<pre><code>import sys
sys.stderr.write('Undesired output.\n')
</code></pre>

<h3>File: <code>script.py</code></h3>

<pre><code>import module
import sys

sys.stderr.write('Desired output.\n')
sys.stdout.write('Desired output.\n')
x = int('a')
</code></pre>

<hr>

<h3>Output of running <code>script.py</code>:</h3>

<pre><code>$ python script.py
Undesired output.
Desired output.
Desired output.
Traceback (most recent call last):
  File "script.py", line 6, in &lt;module&gt;
    x = int('a')
ValueError: invalid literal for int() with base 10: 'a'
</code></pre>

<h3>Desired output of running <code>script.py</code>:</h3>

<pre><code>$ python script.py
Desired output.
Desired output.
Traceback (most recent call last):
  File "script.py", line 6, in &lt;module&gt;
    x = int('a')
ValueError: invalid literal for int() with base 10: 'a'
</code></pre>

<hr>

<p>I cannot modify <code>module.py</code>, but I must use it. I've tried all kinds of redirects, and opening new file descriptors, but I can't seem to change the file descriptors of the calling shell from within python, so</p>

<pre><code>$ python script.py 2&gt;/dev/null
Desired output.
</code></pre>

<p>kills ALL <code>stderr</code> output. Since I know that the module is causing the undesired message, I know exactly which point I want to stop redirecting <code>stderr</code> to <code>/dev/null</code> and start redirecting it to <code>&amp;1</code>, but I can't seem to be able to do it from within Python.</p>

<p>Any advice is much appreciated!</p>

<p>There is an example here in the accepted answer that might help you</p>

<p><a href="http://stackoverflow.com/questions/6796492/temporarily-redirect-stdout-stderr">Temporarily Redirect stdout/stderr</a></p>

<p>but in your case, it assumes that you could do </p>

<pre><code>import module
</code></pre>

<p><em>after</em></p>

<pre><code>import sys
</code></pre>

<p>and <em>after</em> you've redirected stderr in your Python code. Like</p>

<pre><code>import sys

... redirect code here

import module

... code to remove redirect
</code></pre>

<p>Don't know if that will break your desired functionality, beyond the redirects.</p>

<p>Also you're not supposed to stick import statements in the middle of your code, as it violates the PEP8 style guide.</p>

python linux bash file-descriptor io-redirection