本文整理匯總了Python中typing.IO屬性的典型用法代碼示例。如果您正苦於以下問題:Python typing.IO屬性的具體用法?Python typing.IO怎麽用?Python typing.IO使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類typing
的用法示例。
在下文中一共展示了typing.IO屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: decompress_raw_data_by_zcat
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def decompress_raw_data_by_zcat(raw_data_fd: IO, add_bracket: bool = True):
"""Experimental: Decompresses raw data from file like object with zcat. Otherwise same as decompress_raw_data.
Args:
raw_data_fd: File descriptor object.
add_bracket: Whether, or not to add brackets around the output. (Default value = True)
Returns:
A byte array of the decompressed file.
"""
writer = io.BytesIO()
if add_bracket:
writer.write(b'[')
p = subprocess.Popen(["zcat"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
writer.write(p.communicate(input=raw_data_fd.read())[0])
if add_bracket:
writer.write(b']')
return writer.getvalue()
示例2: decompress_raw_data_to_unicode_stream
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def decompress_raw_data_to_unicode_stream(raw_data_fd: IO):
"""Decompresses a raw data in file like object and yields a Unicode string.
Args:
raw_data_fd: File descriptor object.
Yields:
A string of the decompressed file in chunks.
"""
obj = zlib.decompressobj(MAGIC_NUMBER + zlib.MAX_WBITS)
yield '['
d = raw_data_fd.read(CHUNK_SIZE)
while d:
yield obj.decompress(d).decode('utf-8')
while obj.unused_data != b'':
unused_data = obj.unused_data
obj = zlib.decompressobj(MAGIC_NUMBER + zlib.MAX_WBITS)
yield obj.decompress(unused_data).decode('utf-8')
d = raw_data_fd.read(CHUNK_SIZE)
yield obj.flush().decode('utf-8') + ']'
示例3: bfs
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def bfs(self, s: int, t: int) -> IO[str]:
"""Print out the path from Vertex s to Vertex t
using bfs.
"""
if s == t: return
visited = [False] * self._num_vertices
visited[s] = True
q = deque()
q.append(s)
prev = [None] * self._num_vertices
while q:
v = q.popleft()
for neighbour in self._adjacency[v]:
if not visited[neighbour]:
prev[neighbour] = v
if neighbour == t:
print("->".join(self._generate_path(s, t, prev)))
return
visited[neighbour] = True
q.append(neighbour)
示例4: dfs
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def dfs(self, s: int, t: int) -> IO[str]:
"""Print out a path from Vertex s to Vertex t
using dfs.
"""
found = False
visited = [False] * self._num_vertices
prev = [None] * self._num_vertices
def _dfs(from_vertex: int) -> None:
nonlocal found
if found: return
visited[from_vertex] = True
if from_vertex == t:
found = True
return
for neighbour in self._adjacency[from_vertex]:
if not visited[neighbour]:
prev[neighbour] = from_vertex
_dfs(neighbour)
_dfs(s)
print("->".join(self._generate_path(s, t, prev)))
示例5: write_plugin
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def write_plugin(meta: PluginMeta, output: Union[str, IO]) -> None:
with zipfile.ZipFile(output, "w") as zip:
meta_dump = BytesIO()
yaml.dump(meta.serialize(), meta_dump)
zip.writestr("maubot.yaml", meta_dump.getvalue())
for module in meta.modules:
if os.path.isfile(f"{module}.py"):
zip.write(f"{module}.py")
elif module is not None and os.path.isdir(module):
zipdir(zip, module)
else:
print(Fore.YELLOW + f"Module {module} not found, skipping" + Fore.RESET)
for file in meta.extra_files:
zip.write(file)
示例6: read_private_key_file
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def read_private_key_file(file_: IO[str]) -> PKey:
"""Read a private key file. Similar to :meth:`PKey.from_private_key()
<paramiko.pkey.PKey.from_private_key>` except it guess the key type.
:param file_: a stream of the private key to read
:type file_: :class:`~typing.IO`\ [:class:`str`]
:return: the read private key
:rtype: :class:`paramiko.pkey.PKery`
:raise paramiko.ssh_exception.SSHException: when something goes wrong
"""
classes = PKey.__subclasses__()
last = len(classes) + 1
for i, cls in enumerate(KEY_TYPES.values()):
try:
return cls.from_private_key(file_)
except SSHException:
if i == last:
raise
file_.seek(0)
continue
示例7: load
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def load(stream: Union[str, IO]) -> dict:
"""Parse LookML into a Python dictionary.
Args:
stream: File object or string containing LookML to be parsed
Raises:
TypeError: If stream is neither a string or a file object
"""
if isinstance(stream, io.TextIOWrapper):
text = stream.read()
elif isinstance(stream, str):
text = stream
else:
raise TypeError("Input stream must be a string or file object.")
lexer = Lexer(text)
tokens = lexer.scan()
parser = Parser(tokens)
result = parser.parse()
return result
示例8: dump
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def dump(obj: dict, file_object: IO = None) -> Optional[str]:
"""Serialize a Python dictionary into LookML.
Args:
obj: The Python dictionary to be serialized to LookML
file_object: An optional file object to save the LookML string to
Returns:
A LookML string if no file_object is passed
"""
serializer = Serializer()
result = serializer.serialize(obj)
if file_object:
file_object.write(result)
return None
else:
return result
示例9: print_plot_header
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def print_plot_header(self, log_file_ptr: IO[Union[str, bytes]]) -> bool:
"""
Print the plot header.
:param log_file_ptr: File pointer for target output.
:return: True if success
"""
if self.num_gpus()['total'] < 1:
return False
# Print Header
line_str_item = ['Time|Card#']
for table_item in self.table_parameters():
line_str_item.append('|' + table_item)
line_str_item.append('\n')
line_str = ''.join(line_str_item)
log_file_ptr.write(line_str.encode('utf-8'))
log_file_ptr.flush()
return True
示例10: print_plot
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def print_plot(self, log_file_ptr: IO[Union[str, bytes]]) -> bool:
"""
Print the plot data.
:param log_file_ptr: File pointer for target output.
:return: True on success
"""
if self.num_gpus()['total'] < 1:
return False
# Print Data
for gpu in self.gpus():
line_str_item = ['{}|{}'.format(str(gpu.energy['tn'].strftime(env.GUT_CONST.TIME_FORMAT)),
gpu.prm.card_num)]
for table_item in self.table_parameters():
line_str_item.append('|' + re.sub(PATTERNS['MHz'], '', str(gpu.get_params_value(table_item))).strip())
line_str_item.append('\n')
line_str = ''.join(line_str_item)
log_file_ptr.write(line_str.encode('utf-8'))
log_file_ptr.flush()
return True
示例11: hidden_cursor
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def hidden_cursor(file):
# type: (IO) -> Iterator[None]
# The Windows terminal does not support the hide/show cursor ANSI codes,
# even via colorama. So don't even try.
if WINDOWS:
yield
# We don't want to clutter the output with control characters if we're
# writing to a file, or if the user is running with --quiet.
# See https://github.com/pypa/pip/issues/3418
elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
yield
else:
file.write(HIDE_CURSOR)
try:
yield
finally:
file.write(SHOW_CURSOR)
示例12: hidden_cursor
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def hidden_cursor(file):
# type: (IO[Any]) -> Iterator[None]
# The Windows terminal does not support the hide/show cursor ANSI codes,
# even via colorama. So don't even try.
if WINDOWS:
yield
# We don't want to clutter the output with control characters if we're
# writing to a file, or if the user is running with --quiet.
# See https://github.com/pypa/pip/issues/3418
elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
yield
else:
file.write(HIDE_CURSOR)
try:
yield
finally:
file.write(SHOW_CURSOR)
示例13: from_file
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def from_file(
cls, config_file: IO[str], source: str = None, inherit: bool = True
) -> "Theme":
"""Load a theme from a text mode file.
Args:
config_file (IO[str]): An open conf file.
source (str, optional): The filename of the open file. Defaults to None.
inherit (bool, optional): Inherit default styles. Defaults to True.
Returns:
Theme: A New theme instance.
"""
config = configparser.ConfigParser()
config.read_file(config_file, source=source)
styles = {name: Style.parse(value) for name, value in config.items("styles")}
theme = Theme(styles, inherit=inherit)
return theme
示例14: ToRequest
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def ToRequest(
self,
event: event_base.BaseEvent,
converter_type: str,
data_marshaller: typing.Callable,
) -> (dict, typing.IO):
"""
Writes a CloudEvent into a HTTP-ready form of headers and request body
:param event: CloudEvent
:type event: event_base.BaseEvent
:param converter_type: a type of CloudEvent-to-HTTP converter
:type converter_type: str
:param data_marshaller: a callable-like marshaller CloudEvent data
:type data_marshaller: typing.Callable
:return: dict of HTTP headers and stream of HTTP request body
:rtype: tuple
"""
if not isinstance(data_marshaller, typing.Callable):
raise exceptions.InvalidDataMarshaller()
if converter_type in self.__converters_by_type:
cnvrtr = self.__converters_by_type[converter_type]
return cnvrtr.write(event, data_marshaller)
raise exceptions.NoSuchConverter(converter_type)
示例15: upload_container
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import IO [as 別名]
def upload_container(self, record_id: int, field_name: str, file_: IO) -> bool:
"""Uploads the given binary data for the given record id and returns True on success.
Parameters
-----------
record_id : int
The FileMaker record id
field_name : str
Name of the container field on the current layout without TO name. E.g.: my_container
file_ : fileobj
File object as returned by open() in binary mode.
"""
path = API_PATH['record_action'].format(
database=self.database,
layout=self.layout,
record_id=record_id
) + '/containers/' + field_name + '/1'
# requests library handles content type for multipart/form-data incl. boundary
self._set_content_type(False)
self._call_filemaker('POST', path, files={'upload': file_})
return self.last_error == FMSErrorCode.SUCCESS.value