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


Python contextlib.ExitStack类代码示例

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


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

示例1: Function_emitInstructions

def Function_emitInstructions(self):
    self.emitEntry()

    # Exit stack that might contain a selfScope
    self_stack = ExitStack()
    if "self" in self.closed_context:
        assert self.closed_context["self"].llvm_context_index >= 0
        index = self.closed_context["self"].llvm_context_index
        self_value = State.builder.structGEP(self.llvm_context, index, "")
        self_value = State.builder.load(self_value, "")
        self_stack.enter_context(State.selfScope(self_value))

    with self_stack:
        for object in self.closed_context:
            if object.name == "self": continue
            if object.stats.static: continue

            index = object.llvm_context_index
            object.llvm_value = State.builder.structGEP(self.llvm_context, index, "")

        # Allocate Arguments
        for index, arg in enumerate(self.arguments):
            val = self.llvm_value.getParam(index + 1)
            arg.llvm_value = State.builder.alloca(arg.resolveType().emitType(), resolveName(arg))
            State.builder.store(val, arg.llvm_value)

        self.emitPostContext()

        return State.emitInstructions(self.instructions)
开发者ID:pektin,项目名称:jam,代码行数:29,代码来源:emitter.py

示例2: setUp

    def setUp(self):
        super(TestWalkerHandleHandler, self).setUp()
        tmpdir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, tmpdir)

        self.data = {
            "handlercount": 0,
            "frequency": "",
            "handlerdir": tmpdir,
            "handlers": helpers.ContentHandlers(),
            "data": None,
        }

        self.expected_module_name = "part-handler-%03d" % (self.data["handlercount"],)
        expected_file_name = "%s.py" % self.expected_module_name
        self.expected_file_fullname = os.path.join(self.data["handlerdir"], expected_file_name)
        self.module_fake = FakeModule()
        self.ctype = None
        self.filename = None
        self.payload = "dummy payload"

        # Mock the write_file() function.  We'll assert that it got called as
        # expected in each of the individual tests.
        resources = ExitStack()
        self.addCleanup(resources.close)
        self.write_file_mock = resources.enter_context(mock.patch("cloudinit.util.write_file"))
开发者ID:henrysher,项目名称:aws-cloudinit,代码行数:26,代码来源:test__init__.py

示例3: TestZip

class TestZip(unittest.TestCase):
    def setUp(self):
        # Find the path to the example.*.whl so we can add it to the front of
        # sys.path, where we'll then try to find the metadata thereof.
        self.resources = ExitStack()
        self.addCleanup(self.resources.close)
        wheel = self.resources.enter_context(
            path('importlib_metadata.tests.data',
                 'example-21.12-py3-none-any.whl'))
        sys.path.insert(0, str(wheel))
        self.resources.callback(sys.path.pop, 0)

    def test_zip_version(self):
        self.assertEqual(importlib_metadata.version('example'), '21.12')

    def test_zip_entry_points(self):
        parser = importlib_metadata.entry_points('example')
        entry_point = parser.get('console_scripts', 'example')
        self.assertEqual(entry_point, 'example:main')

    def test_missing_metadata(self):
        distribution = importlib_metadata.distribution('example')
        self.assertIsNone(distribution.read_text('does not exist'))

    def test_case_insensitive(self):
        self.assertEqual(importlib_metadata.version('Example'), '21.12')
开发者ID:SerhatG,项目名称:nzbToMedia,代码行数:26,代码来源:test_zip.py

示例4: setUp

    def setUp(self):
        super(TestFindEndpoint, self).setUp()
        patches = ExitStack()
        self.addCleanup(patches.close)

        self.load_file = patches.enter_context(
            mock.patch.object(azure_helper.util, 'load_file'))
开发者ID:akaihola,项目名称:cloud-init,代码行数:7,代码来源:test_azure_helper.py

示例5: logtail

def logtail(path, offset_path=None, *, dry_run=False):
    """Yield new lines from a logfile.

    :param path: The path to the file to read from
    :param offset_path: The path to the file where offset/inode
                        information will be stored.  If not set,
                        ``<file>.offset`` will be used.
    :param dry_run: If ``True``, the offset file will not be modified
                    or created.
    """
    if offset_path is None:
        offset_path = path + '.offset'

    try:
        logfile = open(path, encoding='utf-8', errors='replace')
    except OSError as exc:
        warning_echo('Could not read: {} ({})'.format(path, exc))
        return

    closer = ExitStack()
    closer.enter_context(logfile)
    with closer:
        line_iter = iter([])
        stat = os.stat(logfile.fileno())
        debug_echo('logfile inode={}, size={}'.format(stat.st_ino, stat.st_size))
        inode, offset = _parse_offset_file(offset_path)
        if inode is not None:
            if stat.st_ino == inode:
                debug_echo('inodes are the same')
                if offset == stat.st_size:
                    debug_echo('offset points to eof')
                    return
                elif offset > stat.st_size:
                    warning_echo('File shrunk since last read: {} ({} < {})'.format(path, stat.st_size, offset))
                    offset = 0
            else:
                debug_echo('inode changed, checking for rotated file')
                rotated_path = _check_rotated_file(path, inode)
                if rotated_path is not None:
                    try:
                        rotated_file = open(rotated_path, encoding='utf-8', errors='replace')
                    except OSError as exc:
                        warning_echo('Could not read rotated file: {} ({})'.format(rotated_path, exc))
                    else:
                        closer.enter_context(rotated_file)
                        rotated_file.seek(offset)
                        line_iter = itertools.chain(line_iter, iter(rotated_file))
                offset = 0
        logfile.seek(offset)
        line_iter = itertools.chain(line_iter, iter(logfile))
        for line in line_iter:
            line = line.strip()
            yield line
        pos = logfile.tell()
        debug_echo('reached end of logfile at {}'.format(pos))
        if not dry_run:
            debug_echo('writing offset file: ' + offset_path)
            _write_offset_file(offset_path, stat.st_ino, pos)
        else:
            debug_echo('dry run - not writing offset file')
开发者ID:ThiefMaster,项目名称:logstapo,代码行数:60,代码来源:logtail.py

示例6: target

    def target(self):
        stack = ExitStack()

        for target, value in self.targets:
            stack.enter_context(target.resolveValue().targetValue(value))

        with stack:
            yield
开发者ID:pektin,项目名称:jam,代码行数:8,代码来源:closure.py

示例7: checkCompatibility

    def checkCompatibility(self, other, check_cache = None):
        stack = ExitStack()
        stack.enter_context(self.target())
        if isinstance(other, ClosedTarget):
            stack.enter_context(other.target())
            other = other.value

        with stack:
            return self.value.checkCompatibility(other, check_cache)
开发者ID:pektin,项目名称:jam,代码行数:9,代码来源:closure.py

示例8: Fixture

class Fixture(object):

    def __init__(self, goal, workspace):
        self.fixtures = ExitStack()
        self.goal = goal
        self.workspace = workspace

    def __exit__(self, *args):
        self.fixtures.close()
开发者ID:yaybu,项目名称:touchdown,代码行数:9,代码来源:fixture.py

示例9: test_instance_bypass

    def test_instance_bypass(self):
        class Example(object):
            pass

        cm = Example()
        cm.__exit__ = object()
        stack = ExitStack()
        self.assertRaises(AttributeError, stack.enter_context, cm)
        stack.push(cm)
        self.assertIs(tuple(stack._exit_callbacks)[-1], cm)
开发者ID:edyza,项目名称:micropython-lib,代码行数:10,代码来源:tests.py

示例10: EventLoopThread

class EventLoopThread(object):
    def __init__(self, servers_to_start):
        self.context = None
        self.executor = None
        self.loop = None
        self.servers_to_start = servers_to_start
        self.servers = []

    def __enter__(self):
        self.context = ExitStack()
        self.executor = self.context.enter_context(ThreadPoolExecutor(max_workers=1))
        self.context.enter_context(self.event_loop_context())
        return self

    def __exit__(self, *enc):
        self.context.__exit__(*enc)
        self.context = None
        self.executor = None
        self.loop = None

    def start_loop(self, event):
        logger.info("starting eventloop server")
        loop = asyncio.new_event_loop()
        self.loop = loop
        asyncio.set_event_loop(loop)
        for server_starter in self.servers_to_start:
            server = loop.run_until_complete(server_starter)
            self.servers.append(server)
        loop.call_soon(event.set)
        loop.run_forever()

    def stop_loop(self):
        logger.info("stopping eventloop server")
        self.loop.create_task(self._close_connections())

    @contextmanager
    def event_loop_context(self):
        event = Event()
        event.clear()
        self.executor.submit(self.start_loop, event)
        event.wait()
        logger.info("started eventloop")
        try:
            yield
        finally:
            self.loop.call_soon_threadsafe(self.stop_loop)
            logger.info("stopped eventloop")

    @asyncio.coroutine
    def _close_connections(self):
        for server in self.servers:
            server.close()
            yield from server.wait_closed()
        self.loop.stop()
开发者ID:ksurct,项目名称:MercuryRoboticsEmbedded2016,代码行数:54,代码来源:server.py

示例11: mock_sys

 def mock_sys(self):
     "Mock system environment for InteractiveConsole"
     # use exit stack to match patch context managers to addCleanup
     stack = ExitStack()
     self.addCleanup(stack.close)
     self.infunc = stack.enter_context(mock.patch("code.input", create=True))
     self.stdout = stack.enter_context(mock.patch("code.sys.stdout"))
     self.stderr = stack.enter_context(mock.patch("code.sys.stderr"))
     prepatch = mock.patch("code.sys", wraps=code.sys, spec=code.sys)
     self.sysmod = stack.enter_context(prepatch)
     if sys.excepthook is sys.__excepthook__:
         self.sysmod.excepthook = self.sysmod.__excepthook__
开发者ID:Orav,项目名称:kbengine,代码行数:12,代码来源:test_code_module.py

示例12: __init__

 class StreamDecoder:
     def __init__(self, file):
         self._file = file
         self._crc = 0
         self._pipe = PipeWriter()
         self._cleanup = ExitStack()
         coroutine = self._pipe.coroutine(self._receive())
         self._cleanup.enter_context(coroutine)
     
     def close(self):
         self._pipe.close()
         del self._pipe
         self._cleanup.close()
     
     def feed(self, data):
         self._pipe.write(data)
     
     def _receive(self):
         while True:
             data = self._pipe.buffer
             pos = data.find(b"=")
             if pos >= 0:
                 data = data[:pos]
             data = data.replace(b"\r", b"").replace(b"\n", b"")
             data = data.translate(self.TABLE)
             # TODO: check data size overflow
             self._crc = crc32(data, self._crc)
             self._file.write(data)
             if pos >= 0:  # Escape character (equals sign)
                 self._pipe.buffer = self._pipe.buffer[pos + 1:]
                 while True:
                     byte = yield from self._pipe.read_one()
                     if byte not in b"\r\n":
                         break
                 # TODO: check for size overflow
                 [byte] = byte
                 data = bytes(((byte - 64 - 42) & bitmask(8),))
                 self._crc = crc32(data, self._crc)
                 self._file.write(data)
             else:
                 try:
                     self._pipe.buffer = yield
                 except EOFError:
                     break
     
     def flush(self):
         pass
     
     def getCrc32(self):
         return format(self._crc, "08x")
     
     TABLE = bytes(range(256))
     TABLE = TABLE[-42:] + TABLE[:-42]
开发者ID:vadmium,项目名称:usenet-downloader,代码行数:53,代码来源:yencread.py

示例13: TestSocket

class TestSocket(unittest.TestCase):
    # Usually the socket will be set up from socket.getaddrinfo() but if that
    # raises socket.gaierror, then it tries to infer the IPv4/IPv6 type from
    # the host name.
    def setUp(self):
        self._resources = ExitStack()
        self.addCleanup(self._resources.close)
        self._resources.enter_context(patch('aiosmtpd.main.socket.getaddrinfo',
                                            side_effect=socket.gaierror))

    def test_ipv4(self):
        bind = self._resources.enter_context(patch('aiosmtpd.main.bind'))
        mock_sock = setup_sock('host.example.com', 8025)
        bind.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM, 0)
        mock_sock.bind.assert_called_once_with(('host.example.com', 8025))

    def test_ipv6(self):
        bind = self._resources.enter_context(patch('aiosmtpd.main.bind'))
        mock_sock = setup_sock('::1', 8025)
        bind.assert_called_once_with(socket.AF_INET6, socket.SOCK_STREAM, 0)
        mock_sock.bind.assert_called_once_with(('::1', 8025, 0, 0))

    def test_bind_ipv4(self):
        self._resources.enter_context(patch('aiosmtpd.main.socket.socket'))
        mock_sock = setup_sock('host.example.com', 8025)
        mock_sock.setsockopt.assert_called_once_with(
            socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

    def test_bind_ipv6(self):
        self._resources.enter_context(patch('aiosmtpd.main.socket.socket'))
        mock_sock = setup_sock('::1', 8025)
        self.assertEqual(mock_sock.setsockopt.call_args_list, [
            call(socket.SOL_SOCKET, socket.SO_REUSEADDR, True),
            call(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False),
            ])
开发者ID:davinirjr,项目名称:aiosmtpd,代码行数:35,代码来源:test_main.py

示例14: context_env_update

def context_env_update(context_list, env):
    es = ExitStack()
    for item in context_list:
        # create context manager and enter
        tmp_name = '__pw_cm'
        cm_code = compile(ast.Expression(item.context_expr), '<context_eval>', 'eval')
        env[tmp_name] = es.enter_context(eval(cm_code, env))

        # assign to its optional_vars in separte dict
        if item.optional_vars:
            code = assign_from_ast(item.optional_vars, tmp_name)
            exec(code, env)

    return es
开发者ID:datacamp,项目名称:pythonwhat,代码行数:14,代码来源:tasks.py

示例15: targetValue

    def targetValue(self, value):
        value = value.resolveValue()
        old_value = self.value
        self.value = value

        stack = ExitStack()
        if self._static_value_type is not None:
            targets = [(self._static_value_type, value)]
            stack.enter_context(forward.target(targets))

        with stack:
            yield

        self.value = old_value
开发者ID:pektin,项目名称:jam,代码行数:14,代码来源:variable.py


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