本文整理匯總了Python中contextlib.nested方法的典型用法代碼示例。如果您正苦於以下問題:Python contextlib.nested方法的具體用法?Python contextlib.nested怎麽用?Python contextlib.nested使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類contextlib
的用法示例。
在下文中一共展示了contextlib.nested方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: nested
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def nested(*managers):
exits = []
vars = []
exc = (None, None, None)
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
yield vars
except:
exc = sys.exc_info()
finally:
while exits:
exit = exits.pop()
try:
if exit(*exc):
exc = (None, None, None)
except:
exc = sys.exc_info()
if exc != (None, None, None):
reraise(exc[0], exc[1], exc[2])
示例2: mainloop
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def mainloop(self, display_banner=None):
"""Start the mainloop.
If an optional banner argument is given, it will override the
internally created default banner.
"""
with nested(self.builtin_trap, self.display_trap):
while 1:
try:
self.interact(display_banner=display_banner)
#self.interact_with_readline()
# XXX for testing of a readline-decoupled repl loop, call
# interact_with_readline above
break
except KeyboardInterrupt:
# this should not be necessary, but KeyboardInterrupt
# handling seems rather unpredictable...
self.write("\nKeyboardInterrupt in interact()\n")
示例3: test_query_device_capacity_linux_everything_is_wonderful
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_query_device_capacity_linux_everything_is_wonderful(self):
"""query device capacity works on a happy Linux host"""
with nested(
mock.patch('os.stat'),
mock.patch('stat.S_ISBLK'),
mock.patch('platform.system'),
mock.patch('fcntl.ioctl'),
) as (os_stat, stat_is_block, plat_system, ioctl):
os_stat.return_value = mock.Mock(st_mode=25008)
stat_is_block.return_value = True
plat_system.return_value = 'Linux'
ioctl.return_value = struct.pack('L', 244140625)
# = 'QJ\x8d\x0e\x00\x00\x00\x00'
# = 244140625 ~= 244.140625 MB (in SI)
buffer_test = ' ' * struct.calcsize('L')
bytes = bitmath.query_device_capacity(device)
self.assertEqual(bytes, 244140625)
self.assertEqual(ioctl.call_count, 1)
ioctl.assert_called_once_with(4, 0x80081272, buffer_test)
示例4: test_from_file
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_from_file(self):
update_systrace_trace_viewer.update(force_update=True)
self.assertTrue(os.path.exists(
update_systrace_trace_viewer.SYSTRACE_TRACE_VIEWER_HTML_FILE))
output_file_name = util.generate_random_filename_for_test()
try:
# use from-file to create a specific expected output
run_systrace.main_impl(['./run_systrace.py',
'--from-file',
COMPRESSED_ATRACE_DATA,
'-o',
output_file_name])
# and verify file contents
with contextlib.nested(open(output_file_name, 'r'),
open(DECOMPRESSED_ATRACE_DATA, 'r')) as (f1, f2):
full_trace = f1.read()
expected_contents = f2.read()
self.assertTrue(expected_contents in full_trace)
except:
raise
finally:
os.remove(update_systrace_trace_viewer.SYSTRACE_TRACE_VIEWER_HTML_FILE)
if os.path.exists(output_file_name):
os.remove(output_file_name)
示例5: test_default_output_filename
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_default_output_filename(self):
update_systrace_trace_viewer.update(force_update=True)
self.assertTrue(os.path.exists(
update_systrace_trace_viewer.SYSTRACE_TRACE_VIEWER_HTML_FILE))
output_file_name = os.path.join(TEST_DIR, 'compressed_atrace_data.html')
try:
# use from-file to create a specific expected output
run_systrace.main_impl(['./run_systrace.py',
'--from-file',
COMPRESSED_ATRACE_DATA])
# and verify file contents
with contextlib.nested(open(output_file_name, 'r'),
open(DECOMPRESSED_ATRACE_DATA, 'r')) as (f1, f2):
full_trace = f1.read()
expected_contents = f2.read()
self.assertTrue(expected_contents in full_trace)
except:
raise
finally:
os.remove(update_systrace_trace_viewer.SYSTRACE_TRACE_VIEWER_HTML_FILE)
if os.path.exists(output_file_name):
os.remove(output_file_name)
示例6: test_spawn
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_spawn(self):
self._create_instance()
self._create_network()
with contextlib.nested(
mock.patch.object(EC2Driver, '_get_image_ami_id_from_meta'),
mock.patch.object(EC2Driver, '_process_network_info'),
mock.patch.object(EC2Driver, '_get_instance_sec_grps'),
) as (mock_image, mock_network, mock_secgrp):
mock_image.return_value = 'ami-1234abc'
mock_network.return_value = (self.subnet_id, '192.168.10.5', None,
None)
mock_secgrp.return_value = []
self._create_nova_vm()
fake_instances = self.fake_ec2_conn.get_only_instances()
self.assertEqual(len(fake_instances), 1)
inst = fake_instances[0]
self.assertEqual(inst.vpc_id, self.vpc.id)
self.assertEqual(self.subnet_id, inst.subnet_id)
self.assertEqual(inst.tags['Name'], 'fake_instance')
self.assertEqual(inst.tags['openstack_id'], self.uuid)
self.assertEqual(inst.image_id, 'ami-1234abc')
self.assertEqual(inst.region.name, self.region_name)
self.assertEqual(inst.key_name, 'None')
self.assertEqual(inst.instance_type, 't2.small')
self.reset()
示例7: test_spawn_with_key
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_spawn_with_key(self):
self._create_instance(key_name='fake_key', key_data='fake_key_data')
self._create_network()
with contextlib.nested(
mock.patch.object(EC2Driver, '_get_image_ami_id_from_meta'),
mock.patch.object(EC2Driver, '_process_network_info'),
mock.patch.object(EC2Driver, '_get_instance_sec_grps'),
) as (mock_image, mock_network, mock_secgrp):
mock_image.return_value = 'ami-1234abc'
mock_network.return_value = (self.subnet_id, '192.168.10.5', None,
None)
mock_secgrp.return_value = []
self._create_nova_vm()
fake_instances = self.fake_ec2_conn.get_only_instances()
self.assertEqual(len(fake_instances), 1)
inst = fake_instances[0]
self.assertEqual(inst.key_name, 'fake_key')
self.reset()
示例8: test_destory_instance_terminated_on_aws
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_destory_instance_terminated_on_aws(self):
self._create_vm_in_aws_nova()
fake_instances = self.fake_ec2_conn.get_only_instances()
self.fake_ec2_conn.stop_instances(instance_ids=[fake_instances[0].id])
self.fake_ec2_conn.terminate_instances(
instance_ids=[fake_instances[0].id])
with contextlib.nested(
mock.patch.object(boto.ec2.EC2Connection, 'stop_instances'),
mock.patch.object(boto.ec2.EC2Connection, 'terminate_instances'),
mock.patch.object(EC2Driver, '_wait_for_state'),
) as (fake_stop, fake_terminate, fake_wait):
self.conn.destroy(self.context, self.instance, None, None)
fake_stop.assert_not_called()
fake_terminate.assert_not_called()
fake_wait.assert_not_called()
self.reset()
示例9: mock_response
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def mock_response(self):
with nested(
mock.patch('mycroft.logic.log_source_action.staticconf.read_bool',
autospec=True),
mock.patch('mycroft.logic.log_source_action.staticconf.read_string',
autospec=True),
mock.patch('mycroft.logic.log_source_action.requests.post',
autospec=True)
) as (
read_bool,
read_string,
mock_requests_post
):
read_bool.return_value = False
mock_response = Response()
mock_requests_post.return_value = mock_response
yield mock_response
示例10: close
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def close(self):
print("資源釋放")
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.close()
# import contextlib
# with contextlib.closing(Test()) as t_obj:
# t_obj.t()
# with open("xx.jpg", "rb") as from_file:
# with open("xx2.jpg", "wb") as to_file:
# from_contents = from_file.read()
# to_file.write(from_contents)
# with open("xx.jpg", "rb") as from_file, open("xx2.jpg", "wb") as to_file:
# from_contents = from_file.read()
# to_file.write(from_contents)
# import contextlib
# with contextlib.nested(open("xx.jpg", "rb"), open("xx2.jpg", "wb")) as (from_file, to_file):
# from_contents = from_file.read()
# to_file.write(from_contents)
示例11: test_read_config
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def test_read_config(path, contents, fallback):
def test_case(assertion, msg, mock=None, read_data=None):
with patch("__builtin__.open", mock_open(mock, read_data)):
assert assertion(), msg
test_case(
lambda: sh.read_config(path, fallback) == contents,
"Should read valid YAML",
read_data=yaml.dump(contents, default_flow_style=False)
)
with pytest.raises(IOError) if fallback is None else empty():
test_case(
lambda: sh.read_config(path, fallback) == fallback,
"Should use fallback if file is missing",
MagicMock(side_effect=IOError(errno.ENOENT, ""))
)
with pytest.raises(ParserError):
test_case(
lambda: sh.read_config(path, fallback) is None,
"Should raise error if data is invalid",
read_data="[garbage}",
)
示例12: build_model
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def build_model(inputs, num_classes, is_training, hparams):
"""Constructs the vision model being trained/evaled.
Args:
inputs: input features/images being fed to the image model build built.
num_classes: number of output classes being predicted.
is_training: is the model training or not.
hparams: additional hyperparameters associated with the image model.
Returns:
The logits of the image model.
"""
scopes = setup_arg_scopes(is_training)
with contextlib.nested(*scopes):
if hparams.model_name == 'pyramid_net':
logits = build_shake_drop_model(
inputs, num_classes, is_training)
elif hparams.model_name == 'wrn':
logits = build_wrn_model(
inputs, num_classes, hparams.wrn_size)
elif hparams.model_name == 'shake_shake':
logits = build_shake_shake_model(
inputs, num_classes, hparams, is_training)
return logits
示例13: handle_image_tempfile
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def handle_image_tempfile(self, data, mime):
raw = base64.decodestring(data[mime].encode('ascii'))
imageformat = self._imagemime[mime]
filename = 'tmp.{0}'.format(imageformat)
with nested(NamedFileInTemporaryDirectory(filename),
open(os.devnull, 'w')) as (f, devnull):
f.write(raw)
f.flush()
fmt = dict(file=f.name, format=imageformat)
args = [s.format(**fmt) for s in self.tempfile_image_handler]
subprocess.call(args, stdout=devnull, stderr=devnull)
示例14: nested
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def nested(*context_managers):
enters = []
with ExitStack() as stack:
for manager in context_managers:
enters.append(stack.enter_context(manager))
yield tuple(enters)
示例15: nested
# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import nested [as 別名]
def nested(*contexts):
"""Emulation of contextlib.nested in terms of ExitStack
Has the problems for which "nested" was removed from Python; see:
https://docs.python.org/2/library/contextlib.html#contextlib.nested
But for mock.patch, these do not matter.
"""
with ExitStack() as stack:
yield tuple(stack.enter_context(c) for c in contexts)