本文整理汇总了Python中io.TextIOBase方法的典型用法代码示例。如果您正苦于以下问题:Python io.TextIOBase方法的具体用法?Python io.TextIOBase怎么用?Python io.TextIOBase使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类io
的用法示例。
在下文中一共展示了io.TextIOBase方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_extension
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def _get_extension(file):
"""
Gets the extension for the given file, which can be either a
str or an ``open()``'ed file (which has a ``.name`` attribute).
"""
if isinstance(file, str):
return os.path.splitext(file)[-1]
elif isinstance(file, pathlib.Path):
return file.suffix
elif isinstance(file, bytes):
kind = imghdr.what(io.BytesIO(file))
return ('.' + kind) if kind else ''
elif isinstance(file, io.IOBase) and not isinstance(file, io.TextIOBase) and file.seekable():
kind = imghdr.what(file)
return ('.' + kind) if kind is not None else ''
elif getattr(file, 'name', None):
# Note: ``file.name`` works for :tl:`InputFile` and some `IOBase`
return _get_extension(file.name)
else:
# Maybe it's a Telegram media
return get_extension(file)
示例2: __init__
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def __init__(self, output = sys.stdout, error = sys.stderr):
"""
:param output: Where to write the output; defaults to sys.stdout.
:param error: Where to write any errors; defaults to sys.stderr.
"""
if isinstance(output, TextIOBase):
self._out = output
else:
self._out = TextIOWrapper(output)
if isinstance(error, TextIOBase):
self._err = error
else:
self._err = TextIOWrapper(error)
# has the opening <stream> tag been written yet?
self.header_written = False
示例3: to_file
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def to_file(self, fp, format_, fps=None, **kwargs):
"""
Write subtitle file to file object.
See :meth:`SSAFile.save()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.save()`
or :meth:`SSAFile.to_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :class:`io.TextIOBase` instance.
Note that the file must be opened in text mode (as opposed to binary).
"""
impl = get_format_class(format_)
impl.to_file(self, fp, format_, fps=fps, **kwargs)
# ------------------------------------------------------------------------
# Retiming subtitles
# ------------------------------------------------------------------------
示例4: wrap_file_object
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def wrap_file_object(fileobj):
"""Handle differences in Python 2 and 3 around writing bytes."""
# If it's not an instance of IOBase, we're probably using Python 2 and
# that is less finnicky about writing text versus bytes to a file.
if not isinstance(fileobj, io.IOBase):
return fileobj
# At this point we're using Python 3 and that will mangle text written to
# a file written in bytes mode. So, let's check if the file can handle
# text as opposed to bytes.
if isinstance(fileobj, io.TextIOBase):
return fileobj
# Finally, we've determined that the fileobj passed in cannot handle text,
# so we use TextIOWrapper to handle the conversion for us.
return io.TextIOWrapper(fileobj)
示例5: upload_blob
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def upload_blob(self, contents, overwrite=False, lease=None):
if self.lease is not None:
if lease != self.lease:
raise Exception("Invalid lease!")
if self.contents is None or overwrite is True:
if isinstance(contents, str):
self.contents = contents.encode('utf8')
elif isinstance(contents, io.TextIOBase):
self.contents = contents.read().encode('utf8')
elif isinstance(contents, io.IOBase):
self.contents = contents.read()
elif isinstance(contents, bytes):
self.contents = contents
# Python 2 compatibility - no base class for `file` type
elif hasattr(contents, 'read'):
self.contents = contents.read()
else:
print("Uploading unknown data")
self.contents = contents
示例6: __init__
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def __init__(self, data):
"""
Constructor. Pretty straight forward except for the is_generator check. This is so we
can detect when a function that generates data is passed as a datasource. In this case we
need to exhaust the values in the function generator
"""
if data is None:
data = []
if not hasattr(data, "__iter__"):
raise TypeError(
u"RepeatableIterable must be instantiated with an iterable object"
)
is_generator = hasattr(data, "gi_running") or isinstance(data, io.TextIOBase)
self._data = data if not is_generator else [i for i in data]
self._len = None
self.cycle = itertools.cycle(self._data)
示例7: write_pdb
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def write_pdb(mol, fileobj):
""" Write a PDB file to a buffer
Args:
mol (moldesign.Molecule): molecule to write as pdb
fileobj (io.IOBase): buffer to write to - bytes and text interfaces are acceptable
"""
pmedmol = mol_to_parmed(mol)
tempfile = StringIO()
pmedmol.write_pdb(tempfile, renumber=False)
if not isinstance(fileobj, io.TextIOBase) or 'b' in getattr(fileobj, 'mode', ''):
binaryobj = fileobj
fileobj = io.TextIOWrapper(binaryobj)
wrapped = True
else:
wrapped = False
_insert_conect_records(mol, pmedmol, tempfile, write_to=fileobj)
if wrapped:
fileobj.flush()
fileobj.detach()
示例8: build
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def build(self, src: io.TextIOBase, filename: str, reporter=None):
if reporter:
reporter.heading(2, "C builder")
reporter.message(
"Welcome to the C building report for {}".format(filename)
)
cdialect = self.coptions["std"]
self.logger.info("Starting C compilation (%s)", cdialect)
context = CContext(self.coptions, self.arch_info)
compile_unit = _parse(src, filename, context)
if reporter:
f = io.StringIO()
print_ast(compile_unit, file=f)
reporter.dump_source("C-ast", f.getvalue())
cgen = CCodeGenerator(context)
return cgen.gen_code(compile_unit)
示例9: wasmcompile
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def wasmcompile(source: io.TextIOBase, march, opt_level=2, reporter=None):
""" Webassembly compile """
march = get_arch(march)
if not reporter: # pragma: no cover
reporter = DummyReportGenerator()
wasm_module = read_wasm(source)
ir_module = wasm_to_ir(
wasm_module, march.info.get_type_info("ptr"), reporter=reporter
)
# Optimize:
optimize(ir_module, level=opt_level)
obj = ir_to_object([ir_module], march, reporter=reporter)
return obj
示例10: test_copy_from_propagate_error
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def test_copy_from_propagate_error(self):
class BrokenRead(_base):
def read(self, size):
return 1/0
def readline(self):
return 1/0
curs = self.conn.cursor()
# It seems we cannot do this, but now at least we propagate the error
# self.assertRaises(ZeroDivisionError,
# curs.copy_from, BrokenRead(), "tcopy")
try:
curs.copy_from(BrokenRead(), "tcopy")
except Exception, e:
self.assert_('ZeroDivisionError' in str(e))
示例11: _observe_mdns
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def _observe_mdns(reader, output: io.TextIOBase, verbose: bool):
"""Process the given `reader` for `avahi-browse` events.
IO is mostly isolated in this function; the transformation functions
`_observe_all_in_full` and `_observe_resolver_found` can be tested without
having to deal with IO.
:param reader: A context-manager yielding a `io.TextIOBase`.
"""
if verbose:
observer = _observe_all_in_full
else:
observer = _observe_resolver_found
with reader as infile:
events = _extract_mdns_events(infile)
for event in observer(events):
print(json.dumps(event), file=output, flush=True)
示例12: fileobj_is_binary
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def fileobj_is_binary(f):
"""
Returns True if the give file or file-like object has a file open in binary
mode. When in doubt, returns True by default.
"""
# This is kind of a hack for this to work correctly with _File objects,
# which, for the time being, are *always* binary
if hasattr(f, 'binary'):
return f.binary
if isinstance(f, io.TextIOBase):
return False
mode = fileobj_mode(f)
if mode:
return 'b' in mode
else:
return True
示例13: _gettextwriter
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def _gettextwriter(out, encoding):
if out is None:
import sys
return sys.stdout
if isinstance(out, io.TextIOBase):
# use a text writer as is
return out
# wrap a binary writer with TextIOWrapper
if isinstance(out, io.RawIOBase):
# Keep the original file open when the TextIOWrapper is
# destroyed
class _wrapper:
__class__ = out.__class__
def __getattr__(self, name):
return getattr(out, name)
buffer = _wrapper()
buffer.close = lambda: None
else:
# This is to handle passed objects that aren't in the
# IOBase hierarchy, but just have a write method
buffer = io.BufferedIOBase()
buffer.writable = lambda: True
buffer.write = out.write
try:
# TextIOWrapper uses this methods to determine
# if BOM (for UTF-16, etc) should be added
buffer.seekable = out.seekable
buffer.tell = out.tell
except AttributeError:
pass
return io.TextIOWrapper(buffer, encoding=encoding,
errors='xmlcharrefreplace',
newline='\n',
write_through=True)
示例14: write_to
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def write_to(self, stream):
"""Write an XML representation of self, an ``Event`` object, to the given stream.
The ``Event`` object will only be written if its data field is defined,
otherwise a ``ValueError`` is raised.
:param stream: stream to write XML to.
"""
if self.data is None:
raise ValueError("Events must have at least the data field set to be written to XML.")
event = ET.Element("event")
if self.stanza is not None:
event.set("stanza", self.stanza)
event.set("unbroken", str(int(self.unbroken)))
# if a time isn't set, let Splunk guess by not creating a <time> element
if self.time is not None:
ET.SubElement(event, "time").text = str(self.time)
# add all other subelements to this Event, represented by (tag, text)
subelements = [
("source", self.source),
("sourcetype", self.sourceType),
("index", self.index),
("host", self.host),
("data", self.data)
]
for node, value in subelements:
if value is not None:
ET.SubElement(event, node).text = value
if self.done:
ET.SubElement(event, "done")
if isinstance(stream, TextIOBase):
stream.write(ensure_text(ET.tostring(event)))
else:
stream.write(ET.tostring(event))
stream.flush()
示例15: print_svg
# 需要导入模块: import io [as 别名]
# 或者: from io import TextIOBase [as 别名]
def print_svg(self, filename, *args, **kwargs):
if is_string_like(filename):
fh_to_close = svgwriter = io.open(filename, 'w', encoding='utf-8')
elif is_writable_file_like(filename):
if not isinstance(filename, io.TextIOBase):
if sys.version_info[0] >= 3:
svgwriter = io.TextIOWrapper(filename, 'utf-8')
else:
svgwriter = codecs.getwriter('utf-8')(filename)
else:
svgwriter = filename
fh_to_close = None
else:
raise ValueError("filename must be a path or a file-like object")
return self._print_svg(filename, svgwriter, fh_to_close, **kwargs)