Top-rated recipes tagged "stdout" and "contextmanager"http://code.activestate.com/recipes/tags/stdout+contextmanager/top/2012-01-26T02:14:25-08:00ActiveState Code RecipesContext manager for low-level redirection of stdout/stderr (Python)
2012-01-26T02:14:25-08:00Greg Haskinshttp://code.activestate.com/recipes/users/4176881/http://code.activestate.com/recipes/577564-context-manager-for-low-level-redirection-of-stdou/
<p style="color: grey">
Python
recipe 577564
by <a href="/recipes/users/4176881/">Greg Haskins</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/f2py/">f2py</a>, <a href="/recipes/tags/fortran/">fortran</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/redirect/">redirect</a>, <a href="/recipes/tags/stdout/">stdout</a>).
Revision 3.
</p>
<p>This context manager provides a convenient, Pythonic way to temporarily replace the file descriptors of <code>stdout</code> and <code>stderr</code>, redirecting to either <code>os.devnull</code> or files of your choosing. Swapping the C-level file descriptors is required when suppressing output from compiled extension modules, such as those built using F2PY. It functions equally well for pure-Python code. <em>UPDATE:</em> (see below).</p>
POSIX context manager to temporarily silence, or filter lines from stdout (Python)
2010-03-03T06:17:23-08:00pwallerhttp://code.activestate.com/recipes/users/4173218/http://code.activestate.com/recipes/577083-posix-context-manager-to-temporarily-silence-or-fi/
<p style="color: grey">
Python
recipe 577083
by <a href="/recipes/users/4173218/">pwaller</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/freopen/">freopen</a>, <a href="/recipes/tags/silence/">silence</a>, <a href="/recipes/tags/stdout/">stdout</a>, <a href="/recipes/tags/with/">with</a>).
Revision 2.
</p>
<p>Fed up with libraries you don't have control over emitting text into your precious stdout?</p>
<p>If they use stdout through python, then you can just change sys.stdout to be something else. If they are printing directly to stdout through a C module, or some other means, then you are stuck.</p>
<p>.. at least until you discover the <code>with silence():</code> block!</p>
<p>Caveats: Non-portable, tested only on 2.6 under Linux, uses threading.</p>
<p>Example output:</p>
<pre class="prettyprint"><code>$ python silence_file.py
Before with block..
Sensible stuff!
After the silence block
</code></pre>