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><a href="http://stackoverflow.com/a/39403058/5214181">akubot's answer</a> and some experimentation led me to the answer to this question, so I'm going to accept it.</p>

<p>Do this:</p>

<pre><code>$ exec 3&gt;&amp;1
</code></pre>

<p>Then change <code>script.py</code> to be the following:</p>

<pre><code>import sys, os
sys.stderr = open(os.devnull, 'w')
import module
sys.stderr = os.fdopen(3, 'w')

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

<p>Then run like this:</p>

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

<p>yielding the desired output.</p>

python linux bash file-descriptor io-redirection