Most viewed recipes tagged "context_manager"http://code.activestate.com/recipes/tags/context_manager/views/2013-12-16T21:43:27-08:00ActiveState Code RecipesChangeDirectory context manager (Python)
2009-01-24T12:41:53-08:00Christophe Simonishttp://code.activestate.com/recipes/users/4166953/http://code.activestate.com/recipes/576620-changedirectory-context-manager/
<p style="color: grey">
Python
recipe 576620
by <a href="/recipes/users/4166953/">Christophe Simonis</a>
(<a href="/recipes/tags/change/">change</a>, <a href="/recipes/tags/chdir/">chdir</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/directory/">directory</a>).
Revision 2.
</p>
<p>A context manager that handle a temporary change of the working directory</p>
Use PDFWriter with context manager support (Python)
2013-12-16T21:43:27-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/578790-use-pdfwriter-with-context-manager-support/
<p style="color: grey">
Python
recipe 578790
by <a href="/recipes/users/4173351/">Vasudev Ram</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/reportlab/">reportlab</a>, <a href="/recipes/tags/with_statement/">with_statement</a>, <a href="/recipes/tags/xtopdf/">xtopdf</a>).
</p>
<p>PDFWriter - a core class of the xtopdf toolkit - can now be used with a Python context manager, a.k.a. the Python <strong>with</strong> statement.</p>
<p>Code example below. More details here:</p>
<p><a href="http://jugad2.blogspot.in/2013/12/xtopdf-pdfwriter-now-has-context.html" rel="nofollow">http://jugad2.blogspot.in/2013/12/xtopdf-pdfwriter-now-has-context.html</a></p>
Context 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>
Wrap any iterable context manager so it closes when consumed (Python)
2012-11-19T20:10:35-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/578342-wrap-any-iterable-context-manager-so-it-closes-whe/
<p style="color: grey">
Python
recipe 578342
by <a href="/recipes/users/4184316/">Andrew Barnert</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/iterable/">iterable</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/with_statement/">with_statement</a>).
</p>
<p>There are a few types in Python—most notably, files—that are both iterators and context managers. For trivial cases, these features are easy to use together, but as soon as you need to use the iterator lazily or asynchronously, a with statement won't help. That's where this recipe comes in handy:</p>
<pre class="prettyprint"><code>send_async(with_iter(open(path, 'r')))
</code></pre>
<p>This also allows you to "forward" closing for a wrapped iterator, so closing the outer iterator also closes the inner one:</p>
<pre class="prettyprint"><code>sync_async(line.upper() for line in with_iter(open(path, 'r')))
</code></pre>
Decorator and context manager from a single API (Python)
2010-06-27T15:15:01-07:00Michael Foordhttp://code.activestate.com/recipes/users/2183852/http://code.activestate.com/recipes/577273-decorator-and-context-manager-from-a-single-api/
<p style="color: grey">
Python
recipe 577273
by <a href="/recipes/users/2183852/">Michael Foord</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/with/">with</a>, <a href="/recipes/tags/with_statement/">with_statement</a>).
Revision 12.
</p>
<p>Create objects that act as both context managers <em>and</em> as decorators, and behave the same in both cases.</p>
<p>Works with Python 2.4 - 2.7 and Python 3. The tests require unittest2 or Python 3.2 to run. (And because the tests use the with statement they won't work with Python 2.4.)</p>
<p>Example:</p>
<pre class="prettyprint"><code>from contextdecorator import ContextDecorator
class mycontext(ContextDecorator):
def __init__(self, *args):
"""Normal initialiser"""
def before(self):
"""
Called on entering the with block or starting the decorated function.
If used in a with statement whatever this method returns will be the
context manager.
"""
def after(self, *exc):
"""
Called on exit. Arguments and return value of this method have
the same meaning as the __exit__ method of a normal context
manager.
"""
</code></pre>
<p>Both before and after methods are optional (but providing neither is somewhat pointless). See the tests for more usage examples.</p>
CleanupManager for with statements (Python)
2011-12-18T07:20:46-08:00Nick Coghlanhttp://code.activestate.com/recipes/users/2035254/http://code.activestate.com/recipes/577981-cleanupmanager-for-with-statements/
<p style="color: grey">
Python
recipe 577981
by <a href="/recipes/users/2035254/">Nick Coghlan</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>).
Revision 5.
</p>
<p>Inspired by unittest.TestCase.addCleanup(), CleanupManager provides a means to programmatically add resources to be cleaned up when leaving a with statement. This makes it easy to use with optional resources, and those derived from sequences of inputs.</p>
<p>An more powerful version of this recipe with a few additional features is published under the name <code>ContextStack</code> as part of the contextlib2 module: <a href="http://contextlib2.readthedocs.org" rel="nofollow">http://contextlib2.readthedocs.org</a></p>
<p>This recipe is based on a suggestion originally posted by Nikolaus Rath at <a href="http://bugs.python.org/issue13585" rel="nofollow">http://bugs.python.org/issue13585</a></p>
Context 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>
Context manager to prevent calling code from catching exceptions (Python)
2012-06-17T09:20:56-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/577863-context-manager-to-prevent-calling-code-from-catch/
<p style="color: grey">
Python
recipe 577863
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/exception/">exception</a>).
</p>
<p>The following context manager causes any exceptions raised inside it to print a stack trace and exit immediately. The calling scope is not given a chance to catch the exception.</p>