Popular Python recipes tagged "meta:requires=contextlib"http://code.activestate.com/recipes/langs/python/tags/meta:requires=contextlib/2016-03-23T14:14:26-07:00ActiveState Code RecipesSafely and atomically write to a file (Python)
2016-03-23T14:14:26-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/
<p style="color: grey">
Python
recipe 579097
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/atomic/">atomic</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/save/">save</a>).
Revision 3.
</p>
<p>Saving the user's data is risky. If you write to a file directly, and an error occurs during the write, you may corrupt the file and lose the user's data. One approach to prevent this is to write to a temporary file, then only when you know the file has been written successfully, over-write the original. This function returns a context manager which can make this more convenient.</p>
<p>Update: this now uses <code>os.replace</code> when available, and hopefully will work better on Windows.</p>
Context manager to atomically replace a file (Python)
2012-06-17T12:09:49-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578166-context-manager-to-atomically-replace-a-file/
<p style="color: grey">
Python
recipe 578166
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/atomic/">atomic</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/replace/">replace</a>).
Revision 3.
</p>
<p>This context manager ensures that a file's content is either replaced atomically with new contents or left unchanged. An exception or other error will not leave it empty or with partial content.</p>
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>
File Share Messenger 2.5 (Python)
2011-04-06T02:45:15-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/577638-file-share-messenger-25/
<p style="color: grey">
Python
recipe 577638
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/file_io/">file_io</a>, <a href="/recipes/tags/file_share/">file_share</a>, <a href="/recipes/tags/gui/">gui</a>, <a href="/recipes/tags/messenger/">messenger</a>, <a href="/recipes/tags/network/">network</a>, <a href="/recipes/tags/workaround/">workaround</a>).
</p>
<p>After writing the limited program shown in <a href="http://code.activestate.com/recipes/577637/">recipe 577637</a>, the following program was written with a better yet incompatible I/O system designed not to fill up a file share with many, separate files. This program had five revisions as outlined within the source code. To access settings within this program, use the "F2" key. Documentation may be accessed via the "F1" key (with future plans cut).</p>
<p>If anyone wishes to comment or vote this recipe down, please provide your insight into the fault(s) of the program and provide a suggestion as to what solution you would implement to fix the problems.</p>
Tiny trace/debug-logging tool with smart event filtering (Python)
2011-04-29T02:23:37-07:00Jan Kaliszewskihttp://code.activestate.com/recipes/users/4172762/http://code.activestate.com/recipes/577429-tiny-tracedebug-logging-tool-with-smart-event-filt/
<p style="color: grey">
Python
recipe 577429
by <a href="/recipes/users/4172762/">Jan Kaliszewski</a>
(<a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/trace/">trace</a>).
Revision 3.
</p>
<ul>
<li><p>Just import, call and log your selected call/return/exception/etc. events.</p></li>
<li><p>You can use a standard Python logger from the <code>logging</code> module.</p></li>
<li><p>Quite flexible tool and about 50 efective SLOC only (excluding the example script).</p></li>
<li><p>For debugging rather than production environments (programs noticeably slow down).</p></li>
</ul>
Starting several context managers concurrently (Python)
2010-08-11T14:27:01-07:00Carlos Valientehttp://code.activestate.com/recipes/users/4174637/http://code.activestate.com/recipes/577352-starting-several-context-managers-concurrently/
<p style="color: grey">
Python
recipe 577352
by <a href="/recipes/users/4174637/">Carlos Valiente</a>
.
</p>
<p>This recipe implements the <code>parallel</code> context manager, which executes the <code>__enter__</code> and <code>__exit__</code> method of its arguments concurrently.</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>
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>
A real lockfile implementation (Python)
2008-11-26T00:58:40-08:00Aaron Gallagherhttp://code.activestate.com/recipes/users/4106624/http://code.activestate.com/recipes/576572-a-real-lockfile-implementation/
<p style="color: grey">
Python
recipe 576572
by <a href="/recipes/users/4106624/">Aaron Gallagher</a>
.
</p>
<p>Because I didn't see a good implementation, I've posted here my own implementation of a lockfile context manager. It's POSIX-only because I don't have a Windows machine to test cross-platform atomicity on. Sorry about that.</p>
Fix invalid mail headers when moving from Thunderbird to IMAP (Python)
2008-08-30T20:08:02-07:00Krys Wilkenhttp://code.activestate.com/recipes/users/4166805/http://code.activestate.com/recipes/576471-fix-invalid-mail-headers-when-moving-from-thunderb/
<p style="color: grey">
Python
recipe 576471
by <a href="/recipes/users/4166805/">Krys Wilken</a>
(<a href="/recipes/tags/cyrus/">cyrus</a>, <a href="/recipes/tags/header/">header</a>, <a href="/recipes/tags/imap/">imap</a>, <a href="/recipes/tags/invalid/">invalid</a>, <a href="/recipes/tags/mail/">mail</a>, <a href="/recipes/tags/maildir/">maildir</a>, <a href="/recipes/tags/mbox/">mbox</a>, <a href="/recipes/tags/thunderbird/">thunderbird</a>).
</p>
<p>Removes ">From" and "From " lines from mail headers.</p>
<p>Thunderbird adds invalid mail headers to it's local folders. Cyrus IMAP is strict about them. This script walks through all files in the given directories and removes any line that starts with ">From" or "From " (note the space and no colon).</p>
<p>Requires Python 2.5+.</p>
Rebind (Python)
2008-02-12T05:37:23-08:00Neal Beckerhttp://code.activestate.com/recipes/users/2591287/http://code.activestate.com/recipes/546510-rebind/
<p style="color: grey">
Python
recipe 546510
by <a href="/recipes/users/2591287/">Neal Becker</a>
(<a href="/recipes/tags/shortcuts/">shortcuts</a>).
</p>
<p>Temporarily rebind an attribute using contextmanager</p>
Ruby-style DSL's in Python 2.5 (Python)
2007-11-04T10:35:19-08:00Miklos Hollenderhttp://code.activestate.com/recipes/users/4097594/http://code.activestate.com/recipes/534150-ruby-style-dsls-in-python-25/
<p style="color: grey">
Python
recipe 534150
by <a href="/recipes/users/4097594/">Miklos Hollender</a>
(<a href="/recipes/tags/algorithms/">algorithms</a>).
</p>
<p>The with statement in Python 2.5 can be used similarly to the anonymous blocks of code in Ruby.</p>
Error logging with context manager and decorator (Python)
2007-09-19T06:52:58-07:00Kent Johnsonhttp://code.activestate.com/recipes/users/2016182/http://code.activestate.com/recipes/531821-error-logging-with-context-manager-and-decorator/
<p style="color: grey">
Python
recipe 531821
by <a href="/recipes/users/2016182/">Kent Johnson</a>
(<a href="/recipes/tags/shortcuts/">shortcuts</a>).
</p>
<p>A context manager and decorator that wrap common exception trapping and handling code so they may be applied with just a single line of code in the client.</p>
Switch-like statement construction.. (Python)
2007-06-17T22:15:45-07:00David Weilhttp://code.activestate.com/recipes/users/1296670/http://code.activestate.com/recipes/521914-switch-like-statement-construction/
<p style="color: grey">
Python
recipe 521914
by <a href="/recipes/users/1296670/">David Weil</a>
.
Revision 3.
</p>
<p>This doesn't not intent to be nor became a standard.
Instead it's thought to be a proof of concept for a construction which mimics switch/case statements.
I think it's funny, so, i'll hope you enjoy it as I do.</p>
lexical variables in with-statement (Python)
2007-05-18T06:52:34-07:00Ikkei Shimomurahttp://code.activestate.com/recipes/users/987178/http://code.activestate.com/recipes/520586-lexical-variables-in-with-statement/
<p style="color: grey">
Python
recipe 520586
by <a href="/recipes/users/987178/">Ikkei Shimomura</a>
(<a href="/recipes/tags/programs/">programs</a>).
</p>
Pickle data abstraction using `with' statement (Python)
2007-05-02T04:18:33-07:00sridhttp://code.activestate.com/recipes/users/4053089/http://code.activestate.com/recipes/511510-pickle-data-abstraction-using-with-statement/
<p style="color: grey">
Python
recipe 511510
by <a href="/recipes/users/4053089/">srid</a>
(<a href="/recipes/tags/programs/">programs</a>).
</p>
<p>The <code>pickle' module provides a convenient way to serialize Python data structures to disk. With the introduction of</code>with' statement in Python 2.5, we can write code that reads/updates Python data in a more intuitive way.</p>
Context manager for managing a test file (Python)
2007-03-05T17:53:14-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/502278-context-manager-for-managing-a-test-file/
<p style="color: grey">
Python
recipe 502278
by <a href="/recipes/users/98030/">Brett Cannon</a>
.
</p>
<p>This recipe helps to manage a temporary file used in a test. It returns an open file so as to write the test data, and upon exiting the 'with' statement, makes sure that the created file is deleted.</p>
Context manager for calling a method when exiting a 'with' statement (Python)
2007-01-11T10:58:46-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/499372-context-manager-for-calling-a-method-when-exiting-/
<p style="color: grey">
Python
recipe 499372
by <a href="/recipes/users/98030/">Brett Cannon</a>
(<a href="/recipes/tags/shortcuts/">shortcuts</a>).
</p>
<p>Provides a context manager that allows the user to specify a method on the passed-in object to be called when the 'with' statement is exited. This is a generalization of contextlib.closing.</p>
Implementing the observer pattern yet again: this time with coroutines and the with statement (Python)
2006-11-10T16:38:01-08:00Jim Bakerhttp://code.activestate.com/recipes/users/2810167/http://code.activestate.com/recipes/498259-implementing-the-observer-pattern-yet-again-this-t/
<p style="color: grey">
Python
recipe 498259
by <a href="/recipes/users/2810167/">Jim Baker</a>
(<a href="/recipes/tags/oop/">oop</a>).
</p>
<p>Implements the observer design pattern via generator coroutines, wrapped up to use the new 'with' statement of Python 2.5. Enables the loosely-coupled observation of any container implementing the dictionary protocol.</p>
Time sections of code by using "with" statement (Python)
2006-09-17T23:46:45-07:00Connelly Barneshttp://code.activestate.com/recipes/users/1859269/http://code.activestate.com/recipes/498113-time-sections-of-code-by-using-with-statement/
<p style="color: grey">
Python
recipe 498113
by <a href="/recipes/users/1859269/">Connelly Barnes</a>
(<a href="/recipes/tags/algorithms/">algorithms</a>).
</p>
<p>This recipe allows one to use the "with" statement to time sections of code.</p>