本文整理匯總了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)
示例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)
示例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)))
)
示例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()
示例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
示例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
示例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
)
示例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)
示例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)
示例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
示例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.
示例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)
示例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
示例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)
示例15: __enter__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import ContextManager [as 別名]
def __enter__(self):
# type: () -> ContextManager[Any]
return self