Here are the examples of the python api contextlib.contextmanager taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
171 Examples
3
Example 1
@contextlib.contextmanager
def cd(path):
"""A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
"""
prev_cwd = os.getcwd()
os.chdir(path)
yield
os.chdir(prev_cwd)
3
Example 2
Project: whack Source File: args_test.py
@contextlib.contextmanager
def _updated_env(env):
original_env = os.environ.copy()
for key, value in six.iteritems(env):
os.environ[key] = value
yield
for key in env:
if key in original_env:
os.environ[key] = original_env[value]
else:
del os.environ[key]
3
Example 3
@pytest.fixture(scope='function')
def modify_config(request):
@contextlib.contextmanager
def _modify_config(f, d):
""" Overwrites yaml file ``f`` with values in ``dict`` ``d`` """
orig = yaml.load(open(f, 'r'))
modified = orig.copy()
try:
modified = deep_update(modified, d)
tmpcfg = tempfile.mkstemp(prefix='yatsm_', suffix='.yaml')[1]
yaml.dump(modified, open(tmpcfg, 'w'))
yield tmpcfg
except:
raise
finally:
os.remove(tmpcfg)
return _modify_config
3
Example 4
Project: kokoropy Source File: assertions.py
@contextlib.contextmanager
def assert_execution(self, *rules):
assertsql.asserter.add_rules(rules)
try:
yield
assertsql.asserter.statement_complete()
finally:
assertsql.asserter.clear_rules()
3
Example 5
Project: scikit-neuralnetwork Source File: mlp.py
@contextlib.contextmanager
def _patch_sklearn(self):
# WARNING: Unfortunately, sklearn's LabelBinarizer handles binary data
# as a special case and encodes it very differently to multiclass cases.
# In our case, we want to have 2D outputs when there are 2 classes, or
# the predicted probabilities (e.g. Softmax) will be incorrect.
# The LabelBinarizer is also implemented in a way that this cannot be
# customized without a providing a near-complete rewrite, so here we patch
# the `type_of_target` function for this to work correctly.
import sklearn.preprocessing.label as spl
backup = spl.type_of_target
spl.type_of_target = lambda _: "multiclass"
yield
spl.type_of_target = backup
3
Example 6
@contextlib.contextmanager
def _open(self, get_fileobject):
f = None # make sure f exists even if get_fileobject() fails
try:
success = False
with get_fileobject() as f:
yield f
self.sync(f)
self.commit(f)
success = True
finally:
if not success:
try:
self.rollback(f)
except Exception:
pass
3
Example 7
@contextlib.contextmanager
def redirect_streams(stdout, stderr):
sys.stdout = stdout
sys.stderr = stderr
yield
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
3
Example 8
Project: BruteXSS Source File: initialise.py
@contextlib.contextmanager
def colorama_text(*args, **kwargs):
init(*args, **kwargs)
try:
yield
finally:
deinit()
3
Example 9
Project: bluesky Source File: utils.py
@contextlib.contextmanager
def _print_redirect():
old_stdout = sys.stdout
try:
fout = tempfile.TemporaryFile(mode='w+', encoding='utf-8')
sys.stdout = fout
yield fout
finally:
sys.stdout = old_stdout
3
Example 10
@contextlib.contextmanager
def acquire_write_lock(self):
"""Return the "write" lock context manager.
This will provide a section that is mutexed against
all readers/writers for the dogpile-maintained value.
"""
self.readwritelock.acquire_write_lock()
try:
yield
finally:
self.readwritelock.release_write_lock()
3
Example 11
@contextlib.contextmanager
def _maybe_open(pathOrFile, mode):
if isinstance(pathOrFile, str):
with open(pathOrFile, mode) as fp:
yield fp
else:
yield pathOrFile
3
Example 12
Project: pythonVSCode Source File: common.py
@contextlib.contextmanager
def scale_speed_settings(factor):
a = settings.max_executions
b = settings.max_until_execution_unique
settings.max_executions *= factor
settings.max_until_execution_unique *= factor
try:
yield
finally:
settings.max_executions = a
settings.max_until_execution_unique = b
3
Example 13
def result(self):
"""The result method which returns a context manager
Returns:
ContextManager: The corresponding context manager
"""
if self.exception():
raise self.exception()
# Otherwise return a context manager that cleans up after the block.
@contextlib.contextmanager
def f():
try:
yield self._wrapped.result()
finally:
self._exit_callback()
return f()
3
Example 14
@contextlib.contextmanager #A
def access_time(conn, context):
start = time.time() #B
yield #C
delta = time.time() - start #D
stats = update_stats(conn, context, 'AccessTime', delta) #E
average = stats[1] / stats[0] #F
pipe = conn.pipeline(True)
pipe.zadd('slowest:AccessTime', context, average) #G
pipe.zremrangebyrank('slowest:AccessTime', 0, -101) #H
pipe.execute()
3
Example 15
@contextlib.contextmanager
def _stack_context(self):
try:
yield
except Exception:
self.__failure = sys.exc_info()
self.stop()
3
Example 16
Project: universal-portfolios Source File: tools.py
@contextlib.contextmanager
def mp_pool(n_jobs):
n_jobs = multiprocessing.cpu_count() if n_jobs == -1 else n_jobs
pool = multiprocessing.Pool(n_jobs)
try:
yield pool
finally:
pool.close()
3
Example 17
Project: frescobaldi Source File: documentwatcher.py
@contextlib.contextmanager
def whileSaving(docuement):
"""Temporarily suppress the watching of the docuement during a code block."""
try:
removeUrl(docuement.url())
yield
finally:
addUrl(docuement.url())
3
Example 18
Project: osprey Source File: utils.py
@contextlib.contextmanager
def in_directory(path):
"""Context manager (with statement) that changes the current directory
during the context.
"""
curdir = os.path.abspath(os.curdir)
os.chdir(path)
yield
os.chdir(curdir)
3
Example 19
Project: kazoo Source File: eventlet.py
@contextlib.contextmanager
def _yield_before_after():
# Yield to any other co-routines...
#
# See: http://eventlet.net/doc/modules/greenthread.html
# for how this zero sleep is really a cooperative yield to other potential
# co-routines...
eventlet.sleep(0)
try:
yield
finally:
eventlet.sleep(0)
3
Example 20
@contextlib.contextmanager
def prepare(self):
"""Prepare to install the package.
No-op; should be overridden by subclasses. This function should be a
context manager.
"""
yield
3
Example 21
Project: pykit Source File: utils.py
@contextlib.contextmanager
def passdiff(func):
"""
with passdiff(func):
optimizer.run(func)
"""
before = str(func)
yield
after = str(func)
print(diff(before, after))
3
Example 22
@contextlib.contextmanager
def mkstemp(*args, **kwargs):
"""
Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath
is returned
.. warnings:: Unlike tempfile.mkstemp, this is not secure
"""
fd, filename = tempfile.mkstemp(*args, **kwargs)
os.close(fd)
try:
yield filename
finally:
os.remove(filename)
3
Example 23
@contextlib.contextmanager
def warning():
def _warnformat(msg, category, filename, lineno, file=None, line=None):
return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, msg)
default_warn_format = warnings.formatwarning
try:
warnings.formatwarning = _warnformat
yield warnings.warn
finally:
warnings.formatwarning = default_warn_format
3
Example 24
Project: commcare-hq Source File: build_apps.py
@contextlib.contextmanager
def record_performance_stats(filepath, slug):
hp = hpy()
before = hp.heap()
start = time.clock()
try:
yield
finally:
end = time.clock()
after = hp.heap()
leftover = after - before
with open(filepath, 'a') as f:
f.write('{},{},{}\n'.format(slug, leftover.size, end - start))
3
Example 25
Project: sqlalchemy-redshift Source File: conftest.py
@contextlib.contextmanager
def migrated_database(self):
"""
Test fixture for testing real commits/rollbacks.
Creates and migrates a fresh database for every test.
"""
with self._database() as engine_definition:
engine = engine_definition.engine()
try:
self.migrate(engine)
yield {
'definition': engine_definition,
'engine': engine,
}
finally:
engine.dispose()
3
Example 26
@contextlib.contextmanager
def select_published(self, select_published):
"""Marks a block of publication management."""
self.begin(select_published)
try:
yield
except:
raise
finally:
self.end()
3
Example 27
Project: pip-update-requirements Source File: logging.py
@contextlib.contextmanager
def indent_log(num=2):
"""
A context manager which will cause the log output to be indented for any
log messages emitted inside it.
"""
_log_state.indentation += num
try:
yield
finally:
_log_state.indentation -= num
3
Example 28
Project: pyjade Source File: html.py
@contextlib.contextmanager
def local_context_manager(compiler, local_context):
old_local_context = compiler.local_context
new_local_context = dict(compiler.local_context)
new_local_context.update(local_context)
compiler.local_context = new_local_context
yield
compiler.local_context = old_local_context
3
Example 29
Project: fbuild Source File: __init__.py
@contextlib.contextmanager
def tempfile_link_lib(self, code='', *, quieter=1, ckwargs={}, **kwargs):
with self.tempfile(code) as src:
dst = src.parent / 'temp'
obj = self.uncached_compile(src, quieter=quieter, **ckwargs)
yield self.uncached_link_lib(dst, [obj], quieter=quieter, **kwargs)
3
Example 30
Project: rollingpin Source File: harold.py
@contextlib.contextmanager
def swallow_exceptions(log):
try:
yield
except Exception as e:
log.warning("harold: %s", e)
3
Example 31
@contextlib.contextmanager
def open(name):
ref = sec_keychain_ref()
if name is None:
status = SecKeychainCopyDefault(ref)
msg = "Unable to open default keychain"
else:
status = SecKeychainOpen(name.encode('utf-8'), ref)
msg = "Unable to open keychain {name}".format(**locals())
Error.raise_for_status(status, msg)
try:
yield ref
finally:
_core.CFRelease(ref)
3
Example 32
Project: try Source File: core.py
@contextlib.contextmanager
def use_virtualenv(virtualenv, python_version):
"""Use specific virtualenv."""
try:
if virtualenv:
# check if given directory is a virtualenv
if not os.path.join(virtualenv, "bin/activate"):
raise TryError("Given directory {0} is not a virtualenv.".format(virtualenv))
context.virtualenv_path = virtualenv
yield True
else:
proc = Popen("virtualenv env -p {0} >> {1}".format(python_version, context.logfile),
shell=True, cwd=context.tempdir_path)
context.virtualenv_path = os.path.join(context.tempdir_path, "env")
yield proc.wait() == 0
finally:
context.virtualenv_path = None
3
Example 33
Project: Cnchi Source File: extra.py
@contextlib.contextmanager
def raised_privileges():
""" As regain_privileges/drop_privileges, but in context manager style. """
regain_privileges()
try:
yield
finally:
drop_privileges()
3
Example 34
@contextlib.contextmanager
def add_transform(manager, node, transform, predicate=None):
manager.register_transform(node, transform, predicate)
try:
yield
finally:
manager.unregister_transform(node, transform, predicate)
3
Example 35
Project: selector Source File: fabfile.py
@contextlib.contextmanager
def _freshvirt(virt):
puts(virt)
local('rm -rf %s' % virt)
local('virtualenv --no-site-packages --distribute %s' % virt)
with prefix('. %s/bin/activate' % virt):
with settings(hide('stdout', 'stderr', 'warnings', 'running'),
warn_only=True):
result = local('python -c "import selector"')
if result.return_code != 1:
abort(c.red("Failed to create clean virt without selector."))
yield
3
Example 36
Project: YouCompleteMe Source File: event_notification_test.py
@contextlib.contextmanager
def MockArbitraryBuffer( filetype ):
"""Used via the with statement, set up a single buffer with an arbitrary name
and no contents. Its filetype is set to the supplied filetype."""
# Arbitrary, but valid, single buffer open.
current_buffer = VimBuffer( os.path.realpath( 'TEST_BUFFER' ),
window = 1,
filetype = filetype )
with MockVimBuffers( [ current_buffer ], current_buffer ):
yield
3
Example 37
Project: pledgeservice Source File: test_easy_install.py
@contextlib.contextmanager
def tempdir_context(cd=lambda dir:None):
temp_dir = tempfile.mkdtemp()
orig_dir = os.getcwd()
try:
cd(temp_dir)
yield temp_dir
finally:
cd(orig_dir)
shutil.rmtree(temp_dir)
3
Example 38
@contextlib.contextmanager
def error_handling():
try:
yield
except RepositoryNotClonedError:
logging.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?')
exit(-1)
except CartfileNotFound as e:
logging.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path))
exit(-1)
except NoSuchRevision as e:
logging.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository))
logging.error('Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`')
exit(-1)
except PunicRepresentableError as e:
logging.error(e.message)
exit(-1)
except:
raise
3
Example 39
@contextlib.contextmanager
def working_directory(path):
"""
A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
Original by Greg Warner:
http://code.activestate.com/recipes/576620-changedirectory-context-manager/#c3
"""
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd)
3
Example 40
@contextlib.contextmanager
def __getitem__(self, item):
start = time.time()
try:
yield
finally:
stop = time.time()
self.times[item] += stop - start
3
Example 41
@contextlib.contextmanager
def _open_output(name):
if name is None:
try:
yield Output(sys.stdout)
finally:
sys.stdout.flush()
else:
with open(name, "w") as output:
yield Output(output)
3
Example 42
@contextlib.contextmanager
def _tmp_file(self):
"""Context manager for accessing the content through a temporary file"""
import tempfile
tmp_dir = tempfile.mkdtemp()
tmp_file = os.path.join(tmp_dir, self.filename)
try:
self.save(tmp_file)
yield tmp_file
finally:
if os.path.exists(tmp_file):
os.remove(tmp_file)
os.rmdir(tmp_dir)
3
Example 43
@contextlib.contextmanager
def processing(step):
"""
A context manager. If an :class:`SchemaGenerationException` occurs within
its nested code block, it adds ``step`` to it and reraises.
"""
try:
yield
except SchemaGenerationException as e:
e.steps.appendleft(step)
raise
3
Example 44
Project: ibb Source File: ibb.py
@contextlib.contextmanager
def __overrideOutput(self, new_stdout, new_stderr):
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = new_stdout
sys.stderr = new_stderr
try:
yield
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
3
Example 45
@contextlib.contextmanager
def temporaryFile( contents ):
#
# From the python docuementation:
# Whether the name can be used to open the file a second time, while the
# named temporary file is still open, varies across platforms (it can be
# so used on Unix; it cannot on Windows NT or later).
#
t = tempfile.NamedTemporaryFile( suffix = ".h", delete = False )
t.write( contents )
t.flush()
t.close()
yield t.name
os.unlink(t.name)
3
Example 46
Project: web3.py Source File: ipc.py
@contextlib.contextmanager
def get_ipc_socket(ipc_path, timeout=0.1):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(ipc_path)
sock.settimeout(timeout)
yield sock
sock.close()
3
Example 47
@contextlib.contextmanager
def reset_setup_stop_context():
"""
When the setuptools tests are run using setup.py test, and then
one wants to invoke another setup() command (such as easy_install)
within those tests, it's necessary to reset the global variable
in distutils.core so that the setup() command will run naturally.
"""
setup_stop_after = distutils.core._setup_stop_after
distutils.core._setup_stop_after = None
yield
distutils.core._setup_stop_after = setup_stop_after
3
Example 48
@contextlib.contextmanager
def print_output():
try:
yield
except SystemExit as e:
if STATUS:
print(STATUS)
raise
except Exception as e:
logging.exception('The plugin %s has failed with an unhandled '
'exception', sys.argv[0])
status_err(traceback.format_exc(), force_print=True, exception=e)
else:
if STATUS:
print(STATUS)
for metric in METRICS:
print(metric)
3
Example 49
Project: politwoops-tweet-collector Source File: screenshot-worker.py
@contextlib.contextmanager
def database_cursor(**connect_params):
database = MySQLdb.connect(**connect_params)
log.debug("Connected to database.")
database.autocommit(True) # needed if you're using InnoDB
cursor = database.cursor()
cursor.execute('SET NAMES UTF8')
yield cursor
cursor.close()
database.close()
log.debug("Disconnected from database.")
3
Example 50
Project: kupfer Source File: commandexec.py
@contextlib.contextmanager
def _nesting(self):
try:
self._nest_level += 1
self._delegate = False
yield
finally:
self._nest_level -= 1