當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。