Top-rated recipes tagged "contextlib"http://code.activestate.com/recipes/tags/contextlib/top/2014-08-01T08:28:07-07:00ActiveState Code RecipesContext manager for restoring a value (Python)
2010-01-09T07:14:06-08:00George Sakkishttp://code.activestate.com/recipes/users/2591466/http://code.activestate.com/recipes/576977-context-manager-for-restoring-a-value/
<p style="color: grey">
Python
recipe 576977
by <a href="/recipes/users/2591466/">George Sakkis</a>
(<a href="/recipes/tags/contextlib/">contextlib</a>, <a href="/recipes/tags/context_manager/">context_manager</a>).
Revision 8.
</p>
<p>Often one wants to rebind a name or modify a mutable object, perform a bunch of actions and finally restore the name/object to its original state. An example is redirecting stdout/stderr temporarily (<a href="http://www.diveintopython.org/scripts_and_streams/stdin_stdout_stderr.html" rel="nofollow">http://www.diveintopython.org/scripts_and_streams/stdin_stdout_stderr.html</a>). The <em>restoring</em> context manager shown below simplifies this pattern::</p>
<pre class="prettyprint"><code>import sys
# prints in console
print "hello world!"
with restoring('sys.stdout'):
with open('hello.txt', 'w') as sys.stdout:
# prints in file
print "hello world!"
# prints in console again
print "hello world!"
</code></pre>
Handle exit context manager (Python)
2014-08-01T08:28:07-07:00Giampaolo RodolĂ http://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/577997-handle-exit-context-manager/
<p style="color: grey">
Python
recipe 577997
by <a href="/recipes/users/4178764/">Giampaolo RodolĂ </a>
(<a href="/recipes/tags/atexit/">atexit</a>, <a href="/recipes/tags/contextlib/">contextlib</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/exit/">exit</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/shutdown/">shutdown</a>, <a href="/recipes/tags/sigint/">sigint</a>, <a href="/recipes/tags/signal/">signal</a>, <a href="/recipes/tags/sigterm/">sigterm</a>).
Revision 23.
</p>
<p>A context manager which properly handles SIGTERM (SystemExit) and SIGINT (KeyboardInterrupt) signals, registering a function which is always guaranteed to be called on interpreter exit.
Also, it makes sure to execute previously registered functions as well (if any).</p>