本文整理汇总了Python中typing.TextIO.write方法的典型用法代码示例。如果您正苦于以下问题:Python TextIO.write方法的具体用法?Python TextIO.write怎么用?Python TextIO.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类typing.TextIO
的用法示例。
在下文中一共展示了TextIO.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _update_params
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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)
示例2: write_json_log
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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')
示例3: output_file
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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: save
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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)
示例5: dump_info
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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),
))
示例6: _process_includes
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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)
示例7: _format
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def _format(self, object: object, stream: TextIO, indent: int,
allowance: int, context: Dict[int, int], level: int) -> None:
level = level + 1
objid = _id(object)
if objid in context:
stream.write(_recursion(object))
self._recursive = True
self._readable = False
return
rep = self._repr(object, context, level - 1)
typ = _type(object)
sepLines = _len(rep) > (self._width - 1 - indent - allowance)
write = stream.write
if self._depth and level > self._depth:
write(rep)
return
if sepLines:
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict):
dictobj = cast(dict, object)
write('{')
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
length = _len(dictobj)
if length:
context[objid] = 1
indent = indent + self._indent_per_level
if issubclass(typ, _OrderedDict):
items = list(dictobj.items())
else:
items = sorted(dictobj.items(), key=_safe_tuple)
key, ent = items[0]
rep = self._repr(key, context, level)
write(rep)
write(': ')
self._format(ent, stream, indent + _len(rep) + 2,
allowance + 1, context, level)
if length > 1:
for key, ent in items[1:]:
rep = self._repr(key, context, level)
write(',\n%s%s: ' % (' '*indent, rep))
self._format(ent, stream, indent + _len(rep) + 2,
allowance + 1, context, level)
indent = indent - self._indent_per_level
del context[objid]
write('}')
return
if ((issubclass(typ, list) and r is list.__repr__) or
(issubclass(typ, tuple) and r is tuple.__repr__) or
(issubclass(typ, set) and r is set.__repr__) or
(issubclass(typ, frozenset) and r is frozenset.__repr__)
):
anyobj = Any(object) # TODO Collection?
length = _len(anyobj)
if issubclass(typ, list):
write('[')
endchar = ']'
lst = anyobj
elif issubclass(typ, set):
if not length:
write('set()')
return
write('{')
endchar = '}'
lst = sorted(anyobj, key=_safe_key)
elif issubclass(typ, frozenset):
if not length:
write('frozenset()')
return
write('frozenset({')
endchar = '})'
lst = sorted(anyobj, key=_safe_key)
indent += 10
else:
write('(')
endchar = ')'
lst = list(anyobj)
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
if length:
context[objid] = 1
indent = indent + self._indent_per_level
self._format(lst[0], stream, indent, allowance + 1,
context, level)
if length > 1:
for ent in lst[1:]:
write(',\n' + ' '*indent)
self._format(ent, stream, indent,
allowance + 1, context, level)
indent = indent - self._indent_per_level
del context[objid]
if issubclass(typ, tuple) and length == 1:
write(',')
write(endchar)
return
write(rep)
示例8: export
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def export(self, sounds: Iterable['Sound'], file: TextIO):
"""Write SoundScripts to a file.
Pass a file-like object open for text writing, and an iterable
of Sounds to write to the file.
"""
for snd in sounds:
file.write('"{}"\n\t{{\n'.format(snd.name))
file.write('\t' 'channel {}\n'.format(snd.channel.value))
file.write('\t' 'soundlevel {}\n'.format(join_float(snd.level)))
if snd.volume != (1, 1):
file.write('\tvolume {}\n'.format(join_float(snd.volume)))
if snd.pitch != (100, 100):
file.write('\tpitch {}\n'.format(join_float(snd.pitch)))
if len(snd.sounds) > 1:
file.write('\trandwav\n\t\t{\n')
for wav in snd.sounds:
file.write('\t\twave "{}"\n'.format(wav))
file.write('\t\t}\n')
else:
file.write('\twave "{}"\n'.format(snd.sounds[0]))
if snd.stack_start or snd.stack_stop or snd.stack_update:
file.write(
'\t' 'soundentry_version 2\n'
'\t' 'operator_stacks\n'
'\t\t' '{\n'
)
if snd.stack_start:
file.write(
'\t\t' 'start_stack\n'
'\t\t\t' '{\n'
)
for prop in snd.stack_start:
for line in prop.export():
file.write('\t\t\t' + line)
file.write('\t\t\t}\n')
if snd.stack_update:
file.write(
'\t\t' 'update_stack\n'
'\t\t\t' '{\n'
)
for prop in snd.stack_update:
for line in prop.export():
file.write('\t\t\t' + line)
file.write('\t\t\t}\n')
if snd.stack_stop:
file.write(
'\t\t' 'stop_stack\n'
'\t\t\t' '{\n'
)
for prop in snd.stack_stop:
for line in prop.export():
file.write('\t\t\t' + line)
file.write('\t\t\t}\n')
file.write('\t\t}\n')
file.write('\t}\n')
示例9: writelines_nl
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None:
# Since fileobj.writelines() doesn't add newlines...
# http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file # noqa
fileobj.write('\n'.join(lines) + '\n')
示例10: generate
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
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)
示例11: write
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def write(out: TextIO) -> None:
name = target.name
package = target.package
out.write(PKG_CONFIG.format(**locals()))
示例12: write_to_conll_eval_file
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def write_to_conll_eval_file(prediction_file: TextIO,
gold_file: TextIO,
verb_index: Optional[int],
sentence: List[str],
prediction: List[str],
gold_labels: List[str]):
"""
Prints predicate argument predictions and gold labels for a single verbal
predicate in a sentence to two provided file references.
Parameters
----------
prediction_file : TextIO, required.
A file reference to print predictions to.
gold_file : TextIO, required.
A file reference to print gold labels to.
verb_index : Optional[int], required.
The index of the verbal predicate in the sentence which
the gold labels are the arguments for, or None if the sentence
contains no verbal predicate.
sentence : List[str], required.
The word tokens.
prediction : List[str], required.
The predicted BIO labels.
gold_labels : List[str], required.
The gold BIO labels.
"""
verb_only_sentence = ["-"] * len(sentence)
if verb_index:
verb_only_sentence[verb_index] = sentence[verb_index]
conll_format_predictions = convert_bio_tags_to_conll_format(prediction)
conll_format_gold_labels = convert_bio_tags_to_conll_format(gold_labels)
for word, predicted, gold in zip(verb_only_sentence,
conll_format_predictions,
conll_format_gold_labels):
prediction_file.write(word.ljust(15))
prediction_file.write(predicted.rjust(15) + "\n")
gold_file.write(word.ljust(15))
gold_file.write(gold.rjust(15) + "\n")
prediction_file.write("\n")
gold_file.write("\n")
示例13: dump_conditions
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def dump_conditions(file: TextIO) -> None:
"""Dump docs for all the condition flags, results and metaconditions."""
LOGGER.info('Dumping conditions...')
# Delete existing data, after the marker.
file.seek(0, io.SEEK_SET)
prelude = []
for line in file:
if DOC_MARKER in line:
break
prelude.append(line)
file.seek(0, io.SEEK_SET)
file.truncate(0)
if not prelude:
# No marker, blank the whole thing.
LOGGER.warning('No intro text before marker!')
for line in prelude:
file.write(line)
file.write(DOC_MARKER + '\n\n')
file.write(DOC_META_COND)
ALL_META.sort(key=lambda i: i[1]) # Sort by priority
for flag_key, priority, func in ALL_META:
file.write('#### `{}` ({}):\n\n'.format(flag_key, priority))
dump_func_docs(file, func)
file.write('\n')
for lookup, name in [
(ALL_FLAGS, 'Flags'),
(ALL_RESULTS, 'Results'),
]:
print('<!------->', file=file)
print('# ' + name, file=file)
print('<!------->', file=file)
lookup_grouped = defaultdict(list) # type: Dict[str, List[Tuple[str, Tuple[str, ...], Callable]]]
for flag_key, aliases, func in lookup:
group = getattr(func, 'group', 'ERROR')
if group is None:
group = '00special'
lookup_grouped[group].append((flag_key, aliases, func))
# Collapse 1-large groups into Ungrouped.
for group in list(lookup_grouped):
if len(lookup_grouped[group]) < 2:
lookup_grouped[''].extend(lookup_grouped[group])
del lookup_grouped[group]
if not lookup_grouped['']:
del lookup_grouped['']
for header_ind, (group, funcs) in enumerate(sorted(lookup_grouped.items())):
if group == '':
group = 'Ungrouped Conditions'
if header_ind:
# Not before the first one...
print('---------\n', file=file)
if group == '00special':
print(DOC_SPECIAL_GROUP, file=file)
else:
print('### ' + group + '\n', file=file)
LOGGER.info('Doing {} group...', group)
for flag_key, aliases, func in funcs:
print('#### `{}`:\n'.format(flag_key), file=file)
if aliases:
print('**Aliases:** `' + '`, `'.join(aliases) + '`' + ' \n', file=file)
dump_func_docs(file, func)
file.write('\n')
示例14: render
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def render(self, out: TextIO) -> None:
out.write("}\n")
示例15: generate_bde
# 需要导入模块: from typing import TextIO [as 别名]
# 或者: from typing.TextIO import write [as 别名]
def generate_bde(target: BdeTarget, out: TextIO) -> None:
out.write(LIBRARY_PROLOGUE.format(**locals()))
for component in target.sources():
out.write(' {}\n'.format(component).replace('\\', '/'))
out.write(COMMAND_EPILOGUE)
target_upper = target.name.upper()
out.write(DEFINE_SYMBOL.format(**locals()))
out.write(INCLUDE_DIRECTORIES_PROLOGUE.format(**locals()))
for include in target.includes():
out.write(' {}\n'.format(include).replace('\\', '/'))
out.write(COMMAND_EPILOGUE)
out.write(LINK_LIBRARIES_PROLOGUE.format(**locals()))
for dependency in target.dependencies():
if dependency.has_output:
out.write(' {}\n'.format(dependency.name))
out.write(COMMAND_EPILOGUE)
if target.lazily_bound:
out.write(LAZILY_BOUND_FLAG.format(**locals()))
drivers = []
for driver in target.drivers():
name = os.path.splitext(os.path.basename(driver))[0]
out.write(TESTING_DRIVER.format(**locals()).replace('\\', '/'))
drivers.append(name)
if drivers:
out.write(TEST_TARGET_PROLOGUE.format(**locals()))
for driver in drivers:
out.write(' {}\n'.format(driver))
out.write(COMMAND_EPILOGUE)
out.write(INSTALL_HEADERS_PROLOGUE)
for header in target.headers():
out.write(' {}\n'.format(header).replace('\\', '/'))
out.write(INSTALL_HEADERS_DESTINATION)
out.write(COMMAND_EPILOGUE)
out.write(INSTALL_LIBRARY.format(**locals()))