当前位置: 首页>>代码示例>>Python>>正文


Python contextlib.nested方法代码示例

本文整理汇总了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]) 
开发者ID:jpush,项目名称:jbox,代码行数:25,代码来源:compat.py

示例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") 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:22,代码来源:interactiveshell.py

示例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) 
开发者ID:tbielawa,项目名称:bitmath,代码行数:22,代码来源:test_query_device_capacity.py

示例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) 
开发者ID:FSecureLABS,项目名称:Jandroid,代码行数:26,代码来源:atrace_from_file_agent_unittest.py

示例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) 
开发者ID:FSecureLABS,项目名称:Jandroid,代码行数:24,代码来源:atrace_from_file_agent_unittest.py

示例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() 
开发者ID:platform9,项目名称:openstack-omni,代码行数:27,代码来源:test_driver.py

示例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() 
开发者ID:platform9,项目名称:openstack-omni,代码行数:20,代码来源:test_driver.py

示例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() 
开发者ID:platform9,项目名称:openstack-omni,代码行数:18,代码来源:test_driver.py

示例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 
开发者ID:Yelp,项目名称:mycroft,代码行数:19,代码来源:test_log_source_action.py

示例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) 
开发者ID:wangshunzi,项目名称:Python_code,代码行数:26,代码来源:错误和异常概念.py

示例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}",
        ) 
开发者ID:msanders,项目名称:cider,代码行数:26,代码来源:test_sh.py

示例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 
开发者ID:generalized-iou,项目名称:g-tensorflow-models,代码行数:26,代码来源:train_cifar.py

示例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) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:13,代码来源:interactiveshell.py

示例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) 
开发者ID:pantsbuild,项目名称:pex,代码行数:8,代码来源:compatibility.py

示例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) 
开发者ID:tbielawa,项目名称:bitmath,代码行数:11,代码来源:test_query_device_capacity.py


注:本文中的contextlib.nested方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。