• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python typing.TextIO类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: from_pty

    def from_pty(cls, stdout: TextIO, term: Optional[str] = None) -> 'Vt100_Output':
        """
        Create an Output class from a pseudo terminal.
        (This will take the dimensions by reading the pseudo
        terminal attributes.)
        """
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. For convenience, we print
        # an error message, use standard dimensions, and go on.
        isatty = stdout.isatty()
        fd = stdout.fileno()

        if not isatty and fd not in cls._fds_not_a_terminal:
            msg = 'Warning: Output is not to a terminal (fd=%r).\n'
            sys.stderr.write(msg % fd)
            cls._fds_not_a_terminal.add(fd)

        def get_size() -> Size:
            # If terminal (incorrectly) reports its size as 0, pick a
            # reasonable default.  See
            # https://github.com/ipython/ipython/issues/10071
            rows, columns = (None, None)

            if isatty:
                rows, columns = _get_size(stdout.fileno())
            return Size(rows=rows or 24, columns=columns or 80)

        return cls(stdout, get_size, term=term)
开发者ID:jonathanslenders,项目名称:python-prompt-toolkit,代码行数:28,代码来源:vt100.py


示例2: _update_params

 def _update_params(infile: Iterable[str], outfile: TextIO):
     startday_pattern = ' start time (days)= '
     stopday_pattern = ' stop time (days) = '
     for line in infile:
         if line.startswith(startday_pattern):
             line = '%s%f\n' % (startday_pattern, from_day)
         if line.startswith(stopday_pattern):
             line = '%s%f\n' % (stopday_pattern, to_day)
         outfile.write(line)
开发者ID:4xxi,项目名称:resonances,代码行数:9,代码来源:inputsetters.py


示例3: output_file

def output_file(out: TextIO, fin: TextIO, keep_license: bool) -> None:
	skip = LICENSE_LINES
	if keep_license: skip = 0
	while True:
		line = fin.readline()
		if not line:
			break
		if skip:
			skip -= 1
			continue
		out.write(line)
开发者ID:markuspeloquin,项目名称:javascrypto,代码行数:11,代码来源:build.py


示例4: write_json_log

def write_json_log(jsonlogfile: typing.TextIO, test_name: str, result: TestRun) -> None:
    jresult = {'name': test_name,
               'stdout': result.stdo,
               'result': result.res.value,
               'duration': result.duration,
               'returncode': result.returncode,
               'env': result.env,
               'command': result.cmd}  # type: typing.Dict[str, typing.Any]
    if result.stde:
        jresult['stderr'] = result.stde
    jsonlogfile.write(json.dumps(jresult) + '\n')
开发者ID:mesonbuild,项目名称:meson,代码行数:11,代码来源:mtest.py


示例5: pat_dependency

def pat_dependency(src_path: str, src_file: TextIO) -> str:
  '''
  Return a list of dependencies.
  A .pat file always has a single dependency: the source file it patches.
  '''
  version_line = src_file.readline()
  orig_line = src_file.readline()
  orig_path = orig_line.strip()
  if not orig_path:
    failF('pat error: {}:2:1: line specifying original path is missing or empty.', src_path)
  return orig_path
开发者ID:gwk,项目名称:pat,代码行数:11,代码来源:__init__.py


示例6: save

    def save(self, *, config_fd: TextIO = None, encode: bool = False) -> None:
        with io.StringIO() as config_buffer:
            self.parser.write(config_buffer)
            config = config_buffer.getvalue()
            if encode:
                # Encode config using base64
                config = base64.b64encode(
                    config.encode(sys.getfilesystemencoding())
                ).decode(sys.getfilesystemencoding())

            if config_fd:
                config_fd.write(config)
            else:
                with open(self.save_path(), "w") as f:
                    f.write(config)
开发者ID:mvo5,项目名称:snapcraft,代码行数:15,代码来源:config.py


示例7: load

    def load(self, *, config_fd: TextIO = None) -> None:
        config = ""
        if config_fd:
            config = config_fd.read()
        else:
            # Local configurations (per project) are supposed to be static.
            # That's why it's only checked for 'loading' and never written to.
            # Essentially, all authentication-related changes, like
            # login/logout or macaroon-refresh, will not be persisted for the
            # next runs.
            file_path = ""
            if os.path.exists(LOCAL_CONFIG_FILENAME):
                file_path = LOCAL_CONFIG_FILENAME

                # FIXME: We don't know this for sure when loading the config.
                # Need a better separation of concerns.
                logger.warn(
                    "Using local configuration ({!r}), changes will not be "
                    "persisted.".format(file_path)
                )
            else:
                file_path = BaseDirectory.load_first_config(
                    "snapcraft", "snapcraft.cfg"
                )
            if file_path and os.path.exists(file_path):
                with open(file_path, "r") as f:
                    config = f.read()

        if config:
            _load_potentially_base64_config(self.parser, config)
开发者ID:mvo5,项目名称:snapcraft,代码行数:30,代码来源:config.py


示例8: dump_info

def dump_info(file: TextIO) -> None:
    """Create the wiki page for item options, given a file to write to."""
    print(DOC_HEADER, file=file)
    
    for opt in DEFAULTS:
        if opt.default is None:
            default = ''
        elif type(opt.default) is Vec:
            default = '(`' + opt.default.join(' ') + '`)'
        else:
            default = ' = `' + repr(opt.default) + '`'
        file.write(INFO_DUMP_FORMAT.format(
            id=opt.name, 
            default=default,
            type=TYPE_NAMES[opt.type],
            desc='\n'.join(opt.doc),
        ))
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:17,代码来源:vbsp_options.py


示例9: __init__

    def __init__(self, f: TextIO):
        """
        Create a new `PushbackFile` object to wrap a file-like object.

        **Parameters**

        - `f` (file-like object): A file-like object that contains both a
          `write()` method and a `flush()` method.
        """
        self.__buf = [c for c in ''.join(f.readlines())]
开发者ID:bmc,项目名称:grizzled-python,代码行数:10,代码来源:__init__.py


示例10: _generate_template_to_writer

 def _generate_template_to_writer(self, base: pathlib.Path,
                                  source: pathlib.Path,
                                  writer: TextIO, **extra_variables):
     try:
         template = self.env.get_template(str(source))
     except jinja2.TemplateNotFound as e:
         raise GeneratorError("Template {} not found (search path {})"
                              .format(source,
                                      self._format_search_path())
                              ) from e
     now = datetime.datetime.now(datetime.timezone.utc).astimezone()
     comment = ("Generated on {} from {} by {}"
                .format(now.strftime(self.DATETIME_FORMAT), source,
                        self._current_user))
     relative_source = source.relative_to(base)
     stream = template.stream(**self.config, **extra_variables,
                              comment=comment,
                              source_base=base,
                              source=relative_source,
                              source_dir=relative_source.parent)
     writer.writelines(stream)
开发者ID:agdsn,项目名称:hades,代码行数:21,代码来源:generate.py


示例11: _process_includes

    def _process_includes(self,
                          file_in: TextIO,
                          filename: str,
                          file_out: TextIO) -> None:
        log.debug(f'Processing includes in "{filename}"')

        for line in file_in:
            match = self._include_pattern.search(line)
            if match:
                if self._nested >= self._maxnest:
                    raise MaxNestingExceededError(
                        f'Exceeded maximum include depth of {self._maxnest}'
                    )

                inc_name = match.group(1)
                log.debug(f'Found include directive: {line[:-1]}')
                f, included_name = self._open(inc_name, filename)
                self._nested += 1
                self._process_includes(f, filename, file_out)
                self._nested -= 1
            else:
                file_out.write(line)
开发者ID:bmc,项目名称:grizzled-python,代码行数:22,代码来源:includer.py


示例12: _search

    def _search(self, f: TextIO, filename: Optional[str] = None) -> bool:
        paragraph = []
        last_empty = False
        found = False
        eop_line = None

        def print_paragraph(paragraph: Sequence[str]) -> NoReturn:
            if self._print_file_header:
                print(f'::::::::::\n{filename}\n::::::::::\n')
                self._print_file_header = False
            print('\n'.join(paragraph))
            if self.print_eop and (eop_line is not None):
                print(eop_line)
            else:
                print()

        for line in f.readlines():
            if self.eop_regexp.match(line):
                # End of current paragraph, or a redundent (consecutive)
                # end-of-paragraph mark.  If it's truly the first one since
                # the end of the paragraph, search the accumulated lines of
                # the paragraph.

                if line[-1] == '\n':
                    eop_line = line[:-1]
                else:
                    eop_line = line

                if not last_empty:
                    last_empty = True
                    found = self._search_paragraph(paragraph)
                    if found:
                        print_paragraph(paragraph)
                    paragraph = []

            else:
                # Save this line in the current paragraph buffer
                if line[-1] == '\n':
                    line = line[:-1]
                paragraph += [line]
                last_empty = False

        # We might have a paragraph left in the buffer. If so, search it.

        if not last_empty:
            if self._search_paragraph(paragraph):
                found = True
                print_paragraph(paragraph)

        return found
开发者ID:bmc,项目名称:paragrep,代码行数:50,代码来源:__init__.py


示例13: __init__

    def __init__(self, stdin: TextIO) -> None:
        # Test whether the given input object has a file descriptor.
        # (Idle reports stdin to be a TTY, but fileno() is not implemented.)
        try:
            # This should not raise, but can return 0.
            stdin.fileno()
        except io.UnsupportedOperation:
            if 'idlelib.run' in sys.modules:
                raise io.UnsupportedOperation(
                    'Stdin is not a terminal. Running from Idle is not supported.')
            else:
                raise io.UnsupportedOperation('Stdin is not a terminal.')

        # Even when we have a file descriptor, it doesn't mean it's a TTY.
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. They use for instance
        # pexpect to pipe data into an application. For convenience, we print
        # an error message and go on.
        isatty = stdin.isatty()
        fd = stdin.fileno()

        if not isatty and fd not in Vt100Input._fds_not_a_terminal:
            msg = 'Warning: Input is not to a terminal (fd=%r).\n'
            sys.stderr.write(msg % fd)
            Vt100Input._fds_not_a_terminal.add(fd)

        #
        self.stdin = stdin

        # Create a backup of the fileno(). We want this to work even if the
        # underlying file is closed, so that `typeahead_hash()` keeps working.
        self._fileno = stdin.fileno()

        self._buffer: List[KeyPress] = []  # Buffer to collect the Key objects.
        self.stdin_reader = PosixStdinReader(self._fileno)
        self.vt100_parser = Vt100Parser(
            lambda key_press: self._buffer.append(key_press))
开发者ID:jonathanslenders,项目名称:python-prompt-toolkit,代码行数:37,代码来源:vt100.py


示例14: _prepare_graph_struct

def _prepare_graph_struct(name: Optional[str], graph: TextIO, hosts: List[str], graph_format: str) -> dict:
    if graph_format == 'raw':
        return json.load(graph)
    assert name and hosts, 'Only raw graph format can not set hosts and name'
    result = GraphStruct()
    result.graph_name = name
    result.clusters.from_json({'I': hosts})
    if graph_format == 'script':
        task = ExtendedTaskStruct()
        task.task_name = 'main'
        task.hosts.append('I')
        task.task_struct.executor.name = 'shell'
        executor_cfg = ShellExecutorConfig()
        executor_cfg.shell_script = graph.read()
        task.task_struct.executor.config = executor_cfg.to_json()
        result.tasks.from_json([task.to_json()])
    elif graph_format == 'makefile':
        raise NotImplementedError()
    return result.to_json()
开发者ID:LuckyGeck,项目名称:dedalus,代码行数:19,代码来源:app.py


示例15: load_profiles

def load_profiles(profiles_file: TextIO, person_to_friends: Dict[str, List[str]], \
                  person_to_networks: Dict[str, List[str]]) -> None:
    '''Update the person_to_friends dictionary and the person_to_networks
    dictionary to include data from profiles_file.

    '''
    user = none
    for l in profiles_file.readlines():
        if not user:
            user = to_user(l)
            create_key(user, person_to_friends)
            create_key(user, person_to_networks)
        else:
            if len(l.strip()) == 0:
                user = none
            elif ',' in l:
                person_to_friends[user].append(to_user(l))
            else:
                person_to_networks[user].append(l.strip())
开发者ID:mthomascomp,项目名称:Python-Assignments-,代码行数:19,代码来源:network_functions.py


示例16: map_input

    def map_input(self, data: typing.TextIO) -> libioc.Config.Data.Data:
        """Parse and normalize JSON data."""
        try:
            content = data.read().strip()
        except (FileNotFoundError, PermissionError) as e:
            raise libioc.errors.JailConfigError(
                message=str(e),
                logger=self.logger
            )

        if content == "":
            return libioc.Config.Data.Data()

        try:
            result = json.loads(content)  # type: typing.Dict[str, typing.Any]
            return libioc.Config.Data.Data(result)
        except json.decoder.JSONDecodeError as e:
            raise libioc.errors.JailConfigError(
                message=str(e),
                logger=self.logger
            )
开发者ID:iocage,项目名称:libiocage,代码行数:21,代码来源:JSON.py


示例17: lex

def lex(input: TextIO) -> Iterator[Command]:
    whitespace = re.compile('\s+')

    parsing_item    = False
    parsing_command = False
    command, args   = '', []
    while True:
        char = input.read(1)
        if char is '':
            break
        if whitespace.match(char):
            if parsing_item:
                if parsing_command:
                    args.append('')
                else:
                    command += char
            parsing_item = False
        elif char == '(':
            if parsing_command:
                raise RuntimeError('Nested command')
            args.append('')
            parsing_command = True
            parsing_item    = False
        elif char == ')':
            if not parsing_command:
                raise RuntimeError('Unexpected ")"')
            if args[-1] == '':
                args = args[:-1]
            yield command, args
            command, args   = '', []
            parsing_item    = False
            parsing_command = False
        else:
            if parsing_command:
                args[-1] += char
            else:
                command += char
            parsing_item = True
开发者ID:cppguru,项目名称:bdemeta,代码行数:38,代码来源:cmake_parser.py


示例18: render

 def render(self, out: TextIO) -> None:
     out.write("subgraph %s {\n" % self.name)
     out.write("rank = same\n")
开发者ID:vmiklos,项目名称:ged2dot,代码行数:3,代码来源:ged2dot.py


示例19: stuff

 def stuff(a: TextIO) -> str:
     return a.readline()
开发者ID:Alkalit,项目名称:cpython,代码行数:2,代码来源:test_typing.py


示例20: generate

def generate(targets: List[Target], out: TextIO) -> None:
    uses_pkg_config = any(isinstance(t, Pkg) for t in targets)

    out.write(LISTS_PROLOGUE.format(**locals()))
    out.write(INSTALL_TARGETS)
    if uses_pkg_config:
        out.write('include(FindPkgConfig)\n')

    bde_targets = []
    for target in reversed(targets):
        if isinstance(target, Group) or isinstance(target, Package):
            generate_bde(target, out)
            if len(list(target.drivers())):
                bde_targets.append(target)
        elif isinstance(target, CMake):
            path = target.path()
            out.write('add_subdirectory({path} {target.name})\n'.format(
                                            **locals()).replace('\\', '/'))
        elif isinstance(target, Pkg):
            generate_pkg(target, out)

        if target.overrides:
            out.write(f'include({target.overrides})\n'.replace('\\', '/'))

    if bde_targets:
        out.write(ALL_TESTS_PROLOGUE)
        for target in bde_targets:
            out.write(f'    {target.name}.t\n')
        out.write(COMMAND_EPILOGUE)
开发者ID:frutiger,项目名称:bdemeta,代码行数:29,代码来源:cmake.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python filters.typogrify函数代码示例发布时间:2022-05-27
下一篇:
Python typing.IO类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap