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


Python ExitStack.enter_context方法代码示例

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


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

示例1: Server

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
class Server(object):
    def __init__(self, port):
        self.context = None
        self.thread = None
        self.queue = None
        self.webserver = None
        self.port = port

    def __enter__(self):
        self.context = ExitStack()
        self.context.enter_context(self.event_loop_context())
        self.thread = EventLoopThread([self.webserver.server()])
        self.context.enter_context(self.thread)
        return self

    def __exit__(self, *enc):
        self.context.__exit__(*enc)

    def recv(self):
        result = self.queue.get()
        return result

    def send(self, msg):
        asyncio.run_coroutine_threadsafe(self.webserver.broadcast(msg), self.thread.loop)

    @contextmanager
    def event_loop_context(self):
        with ExitStack() as stack:
            stack.callback(lambda: setattr(self, "queue", None))
            stack.callback(lambda: setattr(self, "webserver", None))
            self.queue = Queue()
            self.webserver = WebsocketServer(self.queue, self.port)
            yield
开发者ID:ksurct,项目名称:MercuryRoboticsEmbedded2016,代码行数:35,代码来源:server.py

示例2: logtail

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
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,代码行数:62,代码来源:logtail.py

示例3: Function_emitInstructions

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
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,代码行数:31,代码来源:emitter.py

示例4: target

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
    def target(self):
        stack = ExitStack()

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

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

示例5: checkCompatibility

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
    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,代码行数:11,代码来源:closure.py

示例6: EventLoopThread

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
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,代码行数:56,代码来源:server.py

示例7: mock_sys

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
 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,代码行数:14,代码来源:test_code_module.py

示例8: __init__

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
 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,代码行数:55,代码来源:yencread.py

示例9: setUp

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
    def setUp(self):
        super(TestOpenSSLManager, self).setUp()
        patches = ExitStack()
        self.addCleanup(patches.close)

        self.subp = patches.enter_context(
            mock.patch.object(azure_helper.util, 'subp'))
        try:
            self.open = patches.enter_context(
                mock.patch('__builtin__.open'))
        except ImportError:
            self.open = patches.enter_context(
                mock.patch('builtins.open'))
开发者ID:akaihola,项目名称:cloud-init,代码行数:15,代码来源:test_azure_helper.py

示例10: TestSocket

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
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,代码行数:37,代码来源:test_main.py

示例11: targetValue

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
    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,代码行数:16,代码来源:variable.py

示例12: PulpWritter

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
class PulpWritter(object):
    """Use this to create a pulp db."""
    def __init__(self, db_name, msg_dumper=None, idx_dumpers=None):
        self.dir_path = os.path.abspath(db_name)
        self.keys_path = os.path.join(self.dir_path, 'keys')
        if os.path.isdir(self.dir_path):
            shutil.rmtree(self.dir_path)
        os.makedirs(self.dir_path)
        os.makedirs(self.keys_path)

        self.master_table = None
        self.key_tables = {}
        self.table_stack = None
        self.msg_dumper = msg_dumper
        self.idx_dumpers = idx_dumpers
    
    def __enter__(self):
        self.table_stack = ExitStack().__enter__()
        table = MasterTable(self.dir_path, 'w', dumper=self.msg_dumper)
        self.add_table(None, table)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.table_stack is not None:
            self.table_stack.close()

    def add_table(self, key, table):
        if key == None:
            self.master_table = table
        else:
            self.key_tables[key] = table
        self.table_stack.enter_context(table)

    def append(self, data, index_map):
        msg_num = self.master_table.append(data)
        for key, value in index_map.items():
            table = self.key_tables.get(key, None)
            if not table:
                if self.idx_dumpers is not None:
                    dumper = self.idx_dumpers.get(key, None)
                else:
                    dumper = None
                table = KeyTable(self.keys_path, key, 'w', dumper=dumper)
                self.add_table(key, table)

            if isinstance(value, (tuple, list, set)):
                for v in value:
                    table.append(v, msg_num)
            else:
                table.append(value, msg_num)
开发者ID:hexforge,项目名称:pulp_db,代码行数:52,代码来源:pulp_db.py

示例13: TestZip

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
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,代码行数:28,代码来源:test_zip.py

示例14: determine_context

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
def determine_context(device_ids: List[int],
                      use_cpu: bool,
                      disable_device_locking: bool,
                      lock_dir: str,
                      exit_stack: ExitStack) -> List[mx.Context]:
    """
    Determine the MXNet context to run on (CPU or GPU).

    :param device_ids: List of device as defined from the CLI.
    :param use_cpu: Whether to use the CPU instead of GPU(s).
    :param disable_device_locking: Disable Sockeye's device locking feature.
    :param lock_dir: Directory to place device lock files in.
    :param exit_stack: An ExitStack from contextlib.
    :return: A list with the context(s) to run on.
    """
    if use_cpu:
        context = [mx.cpu()]
    else:
        num_gpus = get_num_gpus()
        check_condition(num_gpus >= 1,
                        "No GPUs found, consider running on the CPU with --use-cpu "
                        "(note: check depends on nvidia-smi and this could also mean that the nvidia-smi "
                        "binary isn't on the path).")
        if disable_device_locking:
            context = expand_requested_device_ids(device_ids)
        else:
            context = exit_stack.enter_context(acquire_gpus(device_ids, lock_dir=lock_dir))
        context = [mx.gpu(gpu_id) for gpu_id in context]
    return context
开发者ID:lagka,项目名称:sockeye,代码行数:31,代码来源:utils.py

示例15: setUp

# 需要导入模块: from contextlib import ExitStack [as 别名]
# 或者: from contextlib.ExitStack import enter_context [as 别名]
    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,代码行数:28,代码来源:test__init__.py


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