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


Python contextlib.contextmanager方法代码示例

本文整理汇总了Python中contextlib.contextmanager方法的典型用法代码示例。如果您正苦于以下问题:Python contextlib.contextmanager方法的具体用法?Python contextlib.contextmanager怎么用?Python contextlib.contextmanager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在contextlib的用法示例。


在下文中一共展示了contextlib.contextmanager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ensure_safe_environment_variables

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def ensure_safe_environment_variables():
    """
    Get a context manager to safely set environment variables

    All changes will be undone on close, hence environment variables set
    within this contextmanager will neither persist nor change global state.
    """
    saved_environ = dict(os.environ)
    try:
        yield
    finally:
        os.environ.clear()
        os.environ.update(saved_environ)


# -----------------------------------------------------------------------------
# Comparators 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,代码来源:testing.py

示例2: open

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def open(self, mode: QIODevice.OpenMode) -> contextlib.closing:
        """Open the underlying device and ensure opening succeeded.

        Raises OSError if opening failed.

        Args:
            mode: QIODevice::OpenMode flags.

        Return:
            A contextlib.closing() object so this can be used as
            contextmanager.
        """
        ok = self.dev.open(mode)
        if not ok:
            raise QtOSError(self.dev)
        return contextlib.closing(self) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:18,代码来源:qtutils.py

示例3: modify_config

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
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


# RASTER READING UTILS 
开发者ID:ceholden,项目名称:yatsm,代码行数:21,代码来源:conftest.py

示例4: run_xz_decompress

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def run_xz_decompress(stdout, stderr=None):
    """Run xz --decompress and return a contextmanager object for the proc."""
    xz = None
    try:
        xz = subprocess.Popen(["xz", "--decompress", "--stdout"],
                              stdin=subprocess.PIPE, stdout=stdout,
                              stderr=stderr)
        yield xz
    finally:
        if not xz:
            raise OSError("You must have an 'xz' binary in PATH.")

        xz.stdin.close()
        result = xz.wait()

        if result != 0:
            raise IOError("xz --decompress returned %d." % result) 
开发者ID:google,项目名称:rekall,代码行数:19,代码来源:unpack_kdbg_kit.py

示例5: test_position_of_obj_unwraps

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def test_position_of_obj_unwraps():
    import contextlib

    @contextlib.contextmanager
    def cm():
        raise NotImplementedError()

    pdb_ = PdbTest()
    pos = pdb_._get_position_of_obj(cm)

    if hasattr(inspect, "unwrap"):
        assert pos[0] == THIS_FILE_CANONICAL
        assert pos[2] == [
            "    @contextlib.contextmanager\n",
            "    def cm():\n",
            "        raise NotImplementedError()\n",
        ]
    else:
        contextlib_file = contextlib.__file__
        if sys.platform == 'win32':
            contextlib_file = contextlib_file.lower()
        assert pos[0] == contextlib_file.rstrip("c") 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:24,代码来源:test_pdb.py

示例6: test_custom_context_manager

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def test_custom_context_manager(self):
        """Test that @custom_contextmanager is recognized as configured."""
        node = astroid.extract_node(
            """
        from contextlib import contextmanager
        def custom_contextmanager(f):
            return contextmanager(f)
        @custom_contextmanager
        def dec():
            yield
        with dec():
            pass
        """
        )
        with self.assertNoMessages():
            self.checker.visit_with(node) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:18,代码来源:unittest_checker_typecheck.py

示例7: forced_piece_size

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def forced_piece_size(pytestconfig):
    @contextlib.contextmanager
    def _forced_piece_size(piece_size):
        orig_piece_size_min = torf.Torrent.piece_size_min
        torf.Torrent.piece_size_min = piece_size
        with mock.patch('torf.Torrent.piece_size', new_callable=mock.PropertyMock) as mock_piece_size:
            def piece_size_setter(prop, torrent, value):
                torrent.metainfo['info']['piece length'] = piece_size

            mock_piece_size.return_value = piece_size
            mock_piece_size.__set__ = piece_size_setter
            yield piece_size
        torf.Torrent.piece_size_min = orig_piece_size_min
    return _forced_piece_size


# https://stackoverflow.com/a/45690594 
开发者ID:rndusr,项目名称:torf,代码行数:19,代码来源:conftest.py

示例8: test_weak_keys_destroy_while_iterating

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def test_weak_keys_destroy_while_iterating(self):
        # Issue #7105: iterators shouldn't crash when a key is implicitly removed
        dict, objects = self.make_weak_keyed_dict()
        self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys')
        self.check_weak_destroy_while_iterating(dict, objects, 'iteritems')
        self.check_weak_destroy_while_iterating(dict, objects, 'itervalues')
        self.check_weak_destroy_while_iterating(dict, objects, 'iterkeyrefs')
        dict, objects = self.make_weak_keyed_dict()
        @contextlib.contextmanager
        def testcontext():
            try:
                it = iter(dict.iteritems())
                next(it)
                # Schedule a key/value for removal and recreate it
                v = objects.pop().arg
                gc.collect()      # just in case
                yield Object(v), v
            finally:
                it = None           # should commit all removals
                gc.collect()
        self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:23,代码来源:test_weakref.py

示例9: test_weak_values_destroy_while_iterating

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def test_weak_values_destroy_while_iterating(self):
        # Issue #7105: iterators shouldn't crash when a key is implicitly removed
        dict, objects = self.make_weak_valued_dict()
        self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys')
        self.check_weak_destroy_while_iterating(dict, objects, 'iteritems')
        self.check_weak_destroy_while_iterating(dict, objects, 'itervalues')
        self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
        dict, objects = self.make_weak_valued_dict()
        @contextlib.contextmanager
        def testcontext():
            try:
                it = iter(dict.iteritems())
                next(it)
                # Schedule a key/value for removal and recreate it
                k = objects.pop().arg
                gc.collect()      # just in case
                yield k, Object(k)
            finally:
                it = None           # should commit all removals
                gc.collect()
        self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:23,代码来源:test_weakref.py

示例10: setUpClass

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def setUpClass(
        cls,
        launch_service,
        proc_info,
        proc_output,
        rmw_implementation
    ):
        @contextlib.contextmanager
        def launch_action_command(self, arguments):
            action_command_action = ExecuteProcess(
                cmd=['ros2', 'action', *arguments],
                name='ros2action-cli', output='screen',
                additional_env={
                    'RMW_IMPLEMENTATION': rmw_implementation,
                    'PYTHONUNBUFFERED': '1'
                }
            )
            with launch_testing.tools.launch_process(
                launch_service, action_command_action, proc_info, proc_output,
                output_filter=launch_testing_ros.tools.basic_output_filter(
                    filtered_rmw_implementation=rmw_implementation
                )
            ) as action_command:
                yield action_command
        cls.launch_action_command = launch_action_command 
开发者ID:ros2,项目名称:ros2cli,代码行数:27,代码来源:test_cli.py

示例11: setUpClass

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def setUpClass(
        cls,
        launch_service,
        proc_info,
        proc_output
    ):
        @contextlib.contextmanager
        def launch_pkg_command(self, arguments, **kwargs):
            pkg_command_action = ExecuteProcess(
                cmd=['ros2', 'pkg', *arguments],
                additional_env={'PYTHONUNBUFFERED': '1'},
                name='ros2pkg-cli',
                output='screen',
                **kwargs
            )
            with launch_testing.tools.launch_process(
                launch_service, pkg_command_action, proc_info, proc_output
            ) as pkg_command:
                yield pkg_command
        cls.launch_pkg_command = launch_pkg_command 
开发者ID:ros2,项目名称:ros2cli,代码行数:22,代码来源:test_cli.py

示例12: solve_generator

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def solve_generator(
    *, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any]
) -> Any:
    if is_gen_callable(call):
        cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values))
    elif is_async_gen_callable(call):
        if not inspect.isasyncgenfunction(call):
            # asynccontextmanager from the async_generator backfill pre python3.7
            # does not support callables that are not functions or methods.
            # See https://github.com/python-trio/async_generator/issues/32
            #
            # Expand the callable class into its __call__ method before decorating it.
            # This approach will work on newer python versions as well.
            call = getattr(call, "__call__", None)
        cm = asynccontextmanager(call)(**sub_values)
    return await stack.enter_async_context(cm) 
开发者ID:tiangolo,项目名称:fastapi,代码行数:18,代码来源:utils.py

示例13: _patch_AuthAPILdapDataBasedMethodTestMixIn

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def _patch_AuthAPILdapDataBasedMethodTestMixIn():
    @contextlib.contextmanager
    def monkey_patched_standard_context(self, search_flat_return_value):
        create_and_init_db(timeout=20)
        try:
            populate_db_with_test_data(self.__class__.__name__)
            with self._singleton_off():
                self.auth_api = AuthAPI(settings=prepare_auth_db_settings())
                try:
                    with patch.object(AuthAPI, '_get_root_node',
                                      AuthAPI._get_root_node.func):  # unmemoized (not cached)
                        yield
                finally:
                    self.auth_api = None
        finally:
            drop_db()

    def monkey_patched_assert_problematic_orgs_logged(self, *args, **kwargs):
        pass

    test_auth_api._AuthAPILdapDataBasedMethodTestMixIn.standard_context = \
        monkey_patched_standard_context
    test_auth_api._AuthAPILdapDataBasedMethodTestMixIn.assert_problematic_orgs_logged = \
        monkey_patched_assert_problematic_orgs_logged 
开发者ID:CERT-Polska,项目名称:n6,代码行数:26,代码来源:auth_api_with_ldap_api_replacement_quicktest.py

示例14: download_miniconda_installer

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def download_miniconda_installer(installer_url, sha256sum):
    """
    Context manager to download miniconda installer from a given URL

    This should be used as a contextmanager. It downloads miniconda installer
    of given version, verifies the sha256sum & provides path to it to the `with`
    block to run.
    """
    with tempfile.NamedTemporaryFile() as f:
        with open(f.name, 'wb') as f:
            f.write(requests.get(installer_url).content)

        if sha256_file(f.name) != sha256sum:
            raise Exception('sha256sum hash mismatch! Downloaded file corrupted')

        yield f.name 
开发者ID:jupyterhub,项目名称:the-littlest-jupyterhub,代码行数:18,代码来源:conda.py

示例15: testContextManager

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import contextmanager [as 别名]
def testContextManager(self):
    in_context = [False for i in xrange(10)]

    @contextlib.contextmanager
    def enter_into_context(i):
      in_context[i] = True
      try:
        yield
      finally:
        in_context[i] = False

    parallelized_context = parallelizer.SyncParallelizer(
        [enter_into_context(i) for i in xrange(10)])

    with parallelized_context:
      self.assertTrue(all(in_context))
    self.assertFalse(any(in_context)) 
开发者ID:FSecureLABS,项目名称:Jandroid,代码行数:19,代码来源:parallelizer_test.py


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