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


Python typing.ContextManager方法代码示例

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


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

示例1: _handle_error

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def _handle_error(context, *args):
    # type: (Any, *Any) -> None
    conn = context.connection
    span = getattr(conn, "_sentry_sql_span", None)  # type: Optional[Span]

    if span is not None:
        span.set_status("internal_error")

    # _after_cursor_execute does not get called for crashing SQL stmts. Judging
    # from SQLAlchemy codebase it does seem like any error coming into this
    # handler is going to be fatal.
    ctx_mgr = getattr(
        conn, "_sentry_sql_span_manager", None
    )  # type: ContextManager[Any]

    if ctx_mgr is not None:
        conn._sentry_sql_span_manager = None
        ctx_mgr.__exit__(None, None, None) 
开发者ID:getsentry,项目名称:sentry-python,代码行数:20,代码来源:sqlalchemy.py

示例2: push_scope

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def push_scope(  # noqa
        self, callback=None  # type: Optional[Callable[[Scope], None]]
    ):
        # type: (...) -> Optional[ContextManager[Scope]]
        """
        Pushes a new layer on the scope stack.

        :param callback: If provided, this method pushes a scope, calls
            `callback`, and pops the scope again.

        :returns: If no `callback` is provided, a context manager that should
            be used to pop the scope again.
        """
        if callback is not None:
            with self.push_scope() as scope:
                callback(scope)
            return None

        client, scope = self._stack[-1]
        new_layer = (client, copy.copy(scope))
        self._stack.append(new_layer)

        return _ScopeManager(self) 
开发者ID:getsentry,项目名称:sentry-python,代码行数:25,代码来源:hub.py

示例3: path

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def path(
        package: Package, resource: Resource,
        ) -> 'ContextManager[Path]':
    """A context manager providing a file path object to the resource.

    If the resource does not already exist on its own on the file system,
    a temporary file will be created. If the file was created, the file
    will be deleted upon exiting the context manager (no exception is
    raised if the file was deleted prior to the context manager
    exiting).
    """
    reader = _get_resource_reader(_get_package(package))
    return (
        _path_from_reader(reader, resource)
        if reader else
        _common.as_file(files(package).joinpath(_normalize_path(resource)))
        ) 
开发者ID:pypa,项目名称:pipenv,代码行数:19,代码来源:_py3.py

示例4: iterate_output

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def iterate_output(timeout, command):
    # type: (int, Argv) -> ContextManager[Iterator[Text]]
    """
    Run `command` in a subprocess and return a contextmanager of an iterator
    over its output's lines. If `timeout` seconds have passed, iterator ends and
    the process is killed.
    :param timeout: maximum amount of time to wait for command to end
    :param command: command to run
    """
    log.info("running: %s", command)
    process = command.call_subprocess(
        subprocess.Popen, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
    )
    try:
        yield _iterate_output(timeout, process)
    finally:
        status = process.poll()
        if status is not None:
            log.info("command %s terminated, status: %s", command, status)
        else:
            log.info("killing command %s", command)
            process.kill() 
开发者ID:allegroai,项目名称:trains-agent,代码行数:24,代码来源:test_task_script.py

示例5: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def __init__(
            self,
            mode: int,
            ctx: moderngl.Context,
            prog: moderngl.Program,
            dtype: np.dtype,
            draw_context: ContextManager = nullcontext(),
            capacity: int = 256,
            index_capacity: int = 512):
        self.mode = mode
        self.ctx = ctx
        self.prog = prog
        self.dtype = dtype_to_moderngl(dtype)
        self.allocs: Dict[int, Tuple[slice, np.ndarray]] = {}
        self.verts = MemoryBackedBuffer(ctx, capacity, dtype)
        self.indexes = IndexBuffer(ctx)
        self.draw_context = draw_context
        self.dirty = False 
开发者ID:lordmauve,项目名称:wasabi2d,代码行数:20,代码来源:packed.py

示例6: temporarily_download

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def temporarily_download(
    bucket: str, key: str, dir=None
) -> ContextManager[pathlib.Path]:
    """
    Copy a file from S3 to a pathlib.Path; yield; and delete.

    Raise FileNotFoundError if the key is not on S3.

    Usage:

        with minio.temporarily_download('bucket', 'key') as path:
            print(str(path))  # a path on the filesystem
            path.read_bytes()  # returns file contents
        # when you exit the block, the pathlib.Path is deleted
    """
    with tempfile_context(prefix="minio-download-", dir=dir) as path:
        download(bucket, key, path)  # raise FileNotFoundError (deleting path)
        yield path 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:20,代码来源:minio.py

示例7: downloaded_file

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def downloaded_file(stored_object: StoredObject, dir=None) -> ContextManager[Path]:
    """
    Context manager to download and yield `path`, the StoredObject's file.

    Raise FileNotFoundError if the object is missing.

    Usage:

        try:
            with storedobjects.downloaded_file(stored_object) as path:
                # do something with `path`, a `pathlib.Path`
        except FileNotFoundError:
            # file does not exist....
    """
    if stored_object.size == 0:
        # Some stored objects with size=0 do not have key. These are valid:
        # they represent empty files.
        return tempfile_context(prefix="storedobjects-empty-file", dir=dir)
    else:
        # raises FileNotFoundError
        return minio.temporarily_download(
            minio.StoredObjectsBucket, stored_object.key, dir=dir
        ) 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:25,代码来源:io.py

示例8: writable_file

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def writable_file(self, path: Path) -> ContextManager[None]:
        """
        Flag a file as "writable" by a module.

        `path` must exist -- that is, the module must be "overwriting" a file
        (writing to overlayfs, which stores the written file in an output
        layer).

        The logic is: save the original attributes; then make the file
        world-writable. When the context exits, restore the original
        attributes.

        Raise ModuleExitedError if the module tried to inject a symlink.
        """
        old_stat = path.stat()
        path.chmod(0o666)

        try:
            yield
        finally:
            self._reown_output_file(path, old_stat) 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:23,代码来源:chroot.py

示例9: arrow_table_context

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def arrow_table_context(
    table: Union[Dict[str, List[Any]], pyarrow.Table],
    columns: Optional[List[Column]] = None,
    dir: Optional[pathlib.Path] = None,
) -> ContextManager[ArrowTable]:
    """
    Yield an ArrowTable (whose `.path` is a file).

    Metadata is inferred. Number columns have format `{:,}`.
    """
    if isinstance(table, dict):
        table = pyarrow.table(table)

    if columns is None:
        columns = [
            _arrow_column_to_column(name, col)
            for name, col in zip(table.column_names, table.columns)
        ]
    metadata = TableMetadata(table.num_rows, columns)

    if metadata.columns:
        with arrow_file(table, dir=dir) as path:
            yield ArrowTable(path, table, metadata)
    else:
        yield ArrowTable(None, None, metadata) 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:27,代码来源:util.py

示例10: open_text

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def open_text(self, mode='rt', encoding='utf8', errors='strict'):
    # type: (Text, Text, Text) -> ContextManager[TextIO]
    """Return a context manager for opening the file in text mode.

    Args:
      mode: The mode to open the file in. The "t" flag is implicit if not
        already present. It must not have the "b" flag.
      encoding: The encoding to use when opening the file.
      errors: How to handle decoding errors.

    Returns:
      Context manager that yields an open file.

    Raises:
      ValueError: if invalid inputs are provided.
    """
    if 'b' in mode:
      raise ValueError('Invalid mode {!r}: "b" flag not allowed when opening '
                       'file in text mode'.format(mode))
    if 't' not in mode:
      mode += 't'
    cm = self._open(mode, encoding, errors)  # type: ContextManager[TextIO]
    return cm 
开发者ID:abseil,项目名称:abseil-py,代码行数:25,代码来源:absltest.py

示例11: open_bytes

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def open_bytes(self, mode='rb'):
    # type: (Text) -> ContextManager[BinaryIO]
    """Return a context manager for opening the file in binary mode.

    Args:
      mode: The mode to open the file in. The "b" mode is implicit if not
        already present. It must not have the "t" flag.

    Returns:
      Context manager that yields an open file.

    Raises:
      ValueError: if invalid inputs are provided.
    """
    if 't' in mode:
      raise ValueError('Invalid mode {!r}: "t" flag not allowed when opening '
                       'file in binary mode'.format(mode))
    if 'b' not in mode:
      mode += 'b'
    cm = self._open(mode, encoding=None, errors=None)  # type: ContextManager[BinaryIO]
    return cm

  # TODO(b/123775699): Once pytype supports typing.Literal, use overload and
  # Literal to express more precise return types and remove the type comments in
  # open_text and open_bytes. 
开发者ID:abseil,项目名称:abseil-py,代码行数:27,代码来源:absltest.py

示例12: enter_context

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def enter_context(self, manager):
    """Returns the CM's value after registering it with the exit stack.

    Entering a context pushes it onto a stack of contexts. The context is exited
    when the test completes. Contexts are are exited in the reverse order of
    entering. They will always be exited, regardless of test failure/success.
    The context stack is specific to the test being run.

    This is useful to eliminate per-test boilerplate when context managers
    are used. For example, instead of decorating every test with `@mock.patch`,
    simply do `self.foo = self.enter_context(mock.patch(...))' in `setUp()`.

    NOTE: The context managers will always be exited without any error
    information. This is an unfortunate implementation detail due to some
    internals of how unittest runs tests.

    Args:
      manager: The context manager to enter.
    """
    # type: (ContextManager[_T]) -> _T
    if not self._exit_stack:
      raise AssertionError(
          'self._exit_stack is not set: enter_context is Py3-only; also make '
          'sure that AbslTest.setUp() is called.')
    return self._exit_stack.enter_context(manager) 
开发者ID:abseil,项目名称:abseil-py,代码行数:27,代码来源:absltest.py

示例13: command

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def command(self, name):  # type: (str) -> ContextManager[CommandConfig]
        command_config = CommandConfig(name)
        self.add_command_config(command_config)

        yield command_config 
开发者ID:sdispater,项目名称:clikit,代码行数:7,代码来源:application_config.py

示例14: _after_cursor_execute

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def _after_cursor_execute(conn, cursor, statement, *args):
    # type: (Any, Any, Any, *Any) -> None
    ctx_mgr = getattr(
        conn, "_sentry_sql_span_manager", None
    )  # type: ContextManager[Any]

    if ctx_mgr is not None:
        conn._sentry_sql_span_manager = None
        ctx_mgr.__exit__(None, None, None) 
开发者ID:getsentry,项目名称:sentry-python,代码行数:11,代码来源:sqlalchemy.py

示例15: __enter__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ContextManager [as 别名]
def __enter__(self):
        # type: () -> ContextManager[Any]
        return self 
开发者ID:getsentry,项目名称:sentry-python,代码行数:5,代码来源:utils.py


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