Last active
August 29, 2015 14:01
-
-
Save bryan-lott/61575e5118c4e9964c96 to your computer and use it in GitHub Desktop.
Context Manager - Ignore Exceptions and Others
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Not sure where this came from, but I suspect | |
it was from a python talk about making beautiful | |
code.""" | |
from contextlib import contextmanager | |
@contextmanager | |
def ignored(*exceptions): | |
"""Ignore a provided list of exceptions.""" | |
try: | |
yield | |
except exceptions: | |
pass | |
# for other context handler functions, yield can | |
# return a value, ie: | |
tempfilenames = ['test1.txt', 'test2.txt', 'error1.txt'] | |
@contextmanager | |
def create_test_folder(): | |
"""Creates a test directory structure.""" | |
testfolder = tempfile.mkdtemp(suffix='test') | |
test_text = 'temporary test file' | |
for fname in tempfilenames: | |
with open(path.join(testfolder, fname), 'w') as f: | |
f.write(test_text) | |
try: | |
yield testfolder | |
finally: | |
for fname in tempfilenames: | |
os.remove(path.join(testfolder, fname)) | |
os.rmdir(testfolder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment