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


Python typing.IO属性代码示例

本文整理汇总了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() 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:22,代码来源:gzip_decoder.py

示例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') + ']' 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:22,代码来源:gzip_decoder.py

示例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) 
开发者ID:wangzheng0822,项目名称:algo,代码行数:24,代码来源:bfs_dfs.py

示例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))) 
开发者ID:wangzheng0822,项目名称:algo,代码行数:24,代码来源:bfs_dfs.py

示例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) 
开发者ID:maubot,项目名称:maubot,代码行数:18,代码来源:build.py

示例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 
开发者ID:spoqa,项目名称:geofront,代码行数:23,代码来源:masterkey.py

示例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 
开发者ID:joshtemple,项目名称:lkml,代码行数:24,代码来源:__init__.py

示例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 
开发者ID:joshtemple,项目名称:lkml,代码行数:20,代码来源:__init__.py

示例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 
开发者ID:Ricks-Lab,项目名称:gpu-utils,代码行数:21,代码来源:GPUmodule.py

示例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 
开发者ID:Ricks-Lab,项目名称:gpu-utils,代码行数:23,代码来源:GPUmodule.py

示例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) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:19,代码来源:ui.py

示例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) 
开发者ID:pantsbuild,项目名称:pex,代码行数:19,代码来源:ui.py

示例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 
开发者ID:willmcgugan,项目名称:rich,代码行数:20,代码来源:theme.py

示例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) 
开发者ID:cloudevents,项目名称:sdk-python,代码行数:27,代码来源:marshaller.py

示例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 
开发者ID:davidhamann,项目名称:python-fmrest,代码行数:24,代码来源:server.py


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