當前位置: 首頁>>代碼示例>>Python>>正文


Python typing.TextIO方法代碼示例

本文整理匯總了Python中typing.TextIO方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.TextIO方法的具體用法?Python typing.TextIO怎麽用?Python typing.TextIO使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在typing的用法示例。


在下文中一共展示了typing.TextIO方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: yaml_load

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def yaml_load(stream: TextIO, *, safe: bool = True):
    if safe:
        parser = ruamel_yaml.YAML(typ='safe')
    else:
        parser = ruamel_yaml.YAML()

    # first of all, try to parse by ruamel.yaml
    try:
        return parser.load(stream)
    except Exception:
        pass

    # on error try to parse by PyYAML
    if safe:
        return py_yaml.safe_load(stream)
    return py_yaml.load(stream) 
開發者ID:dephell,項目名稱:dephell,代碼行數:18,代碼來源:yaml.py

示例2: citations

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def citations(graph: BELGraph, n: Optional[int] = 15, file: Optional[TextIO] = None) -> None:
    """Print a summary of the citations in the graph."""
    edge_mapping = multidict(
        ((data[CITATION][CITATION_DB], data[CITATION][CITATION_IDENTIFIER]), graph.edge_to_bel(u, v, data))
        for u, v, data in graph.edges(data=True)
        if CITATION in data
    )
    edge_c = Counter({top_level_edge: len(edges) for top_level_edge, edges in edge_mapping.items()})
    df = pd.DataFrame(
        [
            (':'.join(top_level_edge), count, random.choice(edge_mapping[top_level_edge]))  # noqa:S311
            for top_level_edge, count in edge_c.most_common(n=n)
        ],
        columns=['Citation', 'Count', 'Example'],
    )

    if n is None or len(edge_mapping) < n:
        print('{} Citation Count: {}'.format(graph, len(edge_mapping)))
    else:
        print('{} Citation Count: {} (Showing top {})'.format(graph, len(edge_mapping), n))
    print(tabulate(df.values, headers=df.columns), file=file) 
開發者ID:pybel,項目名稱:pybel,代碼行數:23,代碼來源:supersummary.py

示例3: to_triples_file

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def to_triples_file(
    graph: BELGraph,
    path: Union[str, TextIO],
    *,
    use_tqdm: bool = False,
    sep='\t',
    raise_on_none: bool = False
) -> None:
    """Write the graph as a TSV.

    :param graph: A BEL graph
    :param path: A path or file-like
    :param use_tqdm: Should a progress bar be shown?
    :param sep: The separator to use
    :param raise_on_none: Should an exception be raised if no triples are returned?
    :raises: NoTriplesValueError
    """
    for h, r, t in to_triples(graph, use_tqdm=use_tqdm, raise_on_none=raise_on_none):
        print(h, r, t, sep=sep, file=path) 
開發者ID:pybel,項目名稱:pybel,代碼行數:21,代碼來源:api.py

示例4: to_edgelist

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def to_edgelist(
    graph: BELGraph,
    path: Union[str, TextIO],
    *,
    use_tqdm: bool = False,
    sep='\t',
    raise_on_none: bool = False
) -> None:
    """Write the graph as an edgelist.

    :param graph: A BEL graph
    :param path: A path or file-like
    :param use_tqdm: Should a progress bar be shown?
    :param sep: The separator to use
    :param raise_on_none: Should an exception be raised if no triples are returned?
    :raises: NoTriplesValueError
    """
    for h, r, t in to_triples(graph, use_tqdm=use_tqdm, raise_on_none=raise_on_none):
        print(h, t, json.dumps(dict(relation=r)), sep=sep, file=path) 
開發者ID:pybel,項目名稱:pybel,代碼行數:21,代碼來源:api.py

示例5: to_csv

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def to_csv(graph: BELGraph, path: Union[str, TextIO], sep: Optional[str] = None) -> None:
    """Write the graph as a tab-separated edge list.

    The resulting file will contain the following columns:

    1. Source BEL term
    2. Relation
    3. Target BEL term
    4. Edge data dictionary

    See the Data Models section of the documentation for which data are stored in the edge data dictionary, such
    as queryable information about transforms on the subject and object and their associated metadata.
    """
    if sep is None:
        sep = '\t'

    for u, v, data in graph.edges(data=True):
        print(
            graph.edge_to_bel(u, v, edge_data=data, sep=sep),
            json.dumps(data),
            sep=sep,
            file=path,
        ) 
開發者ID:pybel,項目名稱:pybel,代碼行數:25,代碼來源:extras.py

示例6: to_sif

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def to_sif(graph: BELGraph, path: Union[str, TextIO], sep: Optional[str] = None) -> None:
    """Write the graph as a tab-separated SIF file.

    The resulting file will contain the following columns:

    1. Source BEL term
    2. Relation
    3. Target BEL term

    This format is simple and can be used readily with many applications, but is lossy in that it does not include
    relation metadata.
    """
    if sep is None:
        sep = '\t'

    for u, v, data in graph.edges(data=True):
        print(
            graph.edge_to_bel(u, v, edge_data=data, sep=sep),
            file=path,
        ) 
開發者ID:pybel,項目名稱:pybel,代碼行數:22,代碼來源:extras.py

示例7: print_log_header

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def print_log_header(self, log_file_ptr: TextIO) -> bool:
        """
        Print the log header.

        :param log_file_ptr: File pointer for target output.
        :return: True if success
        """
        if self.num_gpus()['total'] < 1:
            return False

        # Print Header
        print('Time|Card#', end='', file=log_file_ptr)
        for table_item in self.table_parameters():
            print('|{}'.format(table_item), end='', file=log_file_ptr)
        print('', file=log_file_ptr)
        return True 
開發者ID:Ricks-Lab,項目名稱:gpu-utils,代碼行數:18,代碼來源:GPUmodule.py

示例8: print_log

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def print_log(self, log_file_ptr: TextIO) -> bool:
        """
        Print the log data.

        :param log_file_ptr: File pointer for target output.
        :return: True if success
        """
        if self.num_gpus()['total'] < 1:
            return False

        # Print Data
        for gpu in self.gpus():
            print('{}|{}'.format(gpu.energy['tn'].strftime(env.GUT_CONST.TIME_FORMAT), gpu.prm.card_num),
                  sep='', end='', file=log_file_ptr)
            for table_item in self.table_parameters():
                print('|{}'.format(re.sub(PATTERNS['MHz'], '', str(gpu.get_params_value(table_item)).strip())),
                      sep='', end='', file=log_file_ptr)
            print('', file=log_file_ptr)
        return True 
開發者ID:Ricks-Lab,項目名稱:gpu-utils,代碼行數:21,代碼來源:GPUmodule.py

示例9: load_resource

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def load_resource(path: str, encoding: str = None) -> TextIO:
    """
    Open a resource file located in a python package or the local filesystem.

    Args:
        path: The resource path in the form of `dir/file` or `package:dir/file`
    Returns:
        A file-like object representing the resource
    """
    components = path.rsplit(":", 1)
    try:
        if len(components) == 1:
            return open(components[0], encoding=encoding)
        else:
            bstream = pkg_resources.resource_stream(components[0], components[1])
            if encoding:
                return TextIOWrapper(bstream, encoding=encoding)
            return bstream
    except IOError:
        pass 
開發者ID:hyperledger,項目名稱:aries-cloudagent-python,代碼行數:22,代碼來源:logging.py

示例10: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def __init__(self, config: Config, file: Optional[TextIO] = None) -> None:
        import _pytest.config

        self.config = config
        self._numcollected = 0
        self._session = None  # type: Optional[Session]
        self._showfspath = None  # type: Optional[bool]

        self.stats = {}  # type: Dict[str, List[Any]]
        self._main_color = None  # type: Optional[str]
        self._known_types = None  # type: Optional[List]
        self.startdir = config.invocation_dir
        if file is None:
            file = sys.stdout
        self._tw = _pytest.config.create_terminal_writer(config, file)
        self._screen_width = self._tw.fullwidth
        self.currentfspath = None  # type: Any
        self.reportchars = getreportopt(config)
        self.hasmarkup = self._tw.hasmarkup
        self.isatty = file.isatty()
        self._progress_nodeids_reported = set()  # type: Set[str]
        self._show_progress_info = self._determine_show_progress_info()
        self._collect_report_last_write = None  # type: Optional[float]
        self._already_displayed_warnings = None  # type: Optional[int]
        self._keyboardinterrupt_memo = None  # type: Optional[ExceptionRepr] 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:27,代碼來源:terminal.py

示例11: create_terminal_writer

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def create_terminal_writer(
    config: Config, file: Optional[TextIO] = None
) -> TerminalWriter:
    """Create a TerminalWriter instance configured according to the options
    in the config object. Every code which requires a TerminalWriter object
    and has access to a config object should use this function.
    """
    tw = TerminalWriter(file=file)
    if config.option.color == "yes":
        tw.hasmarkup = True
    elif config.option.color == "no":
        tw.hasmarkup = False

    if config.option.code_highlight == "yes":
        tw.code_highlight = True
    elif config.option.code_highlight == "no":
        tw.code_highlight = False
    return tw 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:20,代碼來源:__init__.py

示例12: scan_warmup_iters

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def scan_warmup_iters(fd: TextIO, config_dict: Dict, lineno: int) -> int:
    """
    Check warmup iterations, if any.
    """
    if 'save_warmup' not in config_dict:
        return lineno
    cur_pos = fd.tell()
    line = fd.readline().strip()
    draws_found = 0
    while len(line) > 0 and not line.startswith('#'):
        lineno += 1
        draws_found += 1
        cur_pos = fd.tell()
        line = fd.readline().strip()
    fd.seek(cur_pos)
    config_dict['draws_warmup'] = draws_found
    return lineno 
開發者ID:stan-dev,項目名稱:cmdstanpy,代碼行數:19,代碼來源:utils.py

示例13: scan_sampling_iters

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def scan_sampling_iters(fd: TextIO, config_dict: Dict, lineno: int) -> int:
    """
    Parse sampling iteration, save number of iterations to config_dict.
    """
    draws_found = 0
    num_cols = len(config_dict['column_names'])
    cur_pos = fd.tell()
    line = fd.readline().strip()
    while len(line) > 0 and not line.startswith('#'):
        lineno += 1
        draws_found += 1
        data = line.split(',')
        if len(data) != num_cols:
            raise ValueError(
                'line {}: bad draw, expecting {} items, found {}'.format(
                    lineno, num_cols, len(line.split(','))
                )
            )
        cur_pos = fd.tell()
        line = fd.readline().strip()
    config_dict['draws_sampling'] = draws_found
    fd.seek(cur_pos)
    return lineno 
開發者ID:stan-dev,項目名稱:cmdstanpy,代碼行數:25,代碼來源:utils.py

示例14: _resolveMarkupInclusions

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def _resolveMarkupInclusions(
    src: Union[TextIO, pathlib.Path], root: Optional[pathlib.Path] = None
) -> Tuple[io.StringIO, List[Tuple[pathlib.Path, FileMark]]]:
    root = _getRootFromSrc(src, root)

    if isinstance(src, pathlib.Path):
        # this is inefficient, but avoids having to play with io buffers
        with open(src, "r") as rootFile:
            src = io.StringIO(rootFile.read())

    out = io.StringIO()
    includes = []
    _processIncludes(src, out, includes, root)

    out.seek(0)
    # be kind; rewind
    src.seek(0)

    return out, includes 
開發者ID:terrapower,項目名稱:armi,代碼行數:21,代碼來源:textProcessors.py

示例15: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import TextIO [as 別名]
def __init__(self, file_to: TextIO) -> None:
        self._file_to = file_to 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:4,代碼來源:output_generator.py


注:本文中的typing.TextIO方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。