Skip to content

Instantly share code, notes, and snippets.

@travisbhartwell
Created February 5, 2009 00:31
Show Gist options
  • Save travisbhartwell/58442 to your computer and use it in GitHub Desktop.
Save travisbhartwell/58442 to your computer and use it in GitHub Desktop.
rom __future__ import with_statement
from contextlib import contextmanager
import sys
@contextmanager
def open_with_stderr(filename, mode='r'):
try:
f = open(filename, mode)
yield f
except:
print >> sys.stderr, "Problems loading from %s" % filename
else:
f.close()
raise
---------------
With this output:
$ python2.5 foo/diskreport.py foo.xml
Problems loading from foo.xml
Traceback (most recent call last):
File "foo/diskreport.py", line 70, in <module>
with open_with_stderr(xml_filename, 'r') as xml_file:
File "/usr/lib/python2.5/contextlib.py", line 17, in __enter__
raise RuntimeError("generator didn't yield")
RuntimeError: generator didn't yield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment