本文整理汇总了Python中typing.TextIO类的典型用法代码示例。如果您正苦于以下问题:Python TextIO类的具体用法?Python TextIO怎么用?Python TextIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TextIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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)
示例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')
示例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
示例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)
示例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)
示例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),
))
示例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())]
示例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)
示例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)
示例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
示例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))
示例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()
示例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())