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


Python io.TextIOBase方法代碼示例

本文整理匯總了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) 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:23,代碼來源:utils.py

示例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 
開發者ID:gjanders,項目名稱:SplunkAdmins,代碼行數:19,代碼來源:event_writer.py

示例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
    # ------------------------------------------------------------------------ 
開發者ID:tkarabela,項目名稱:pysubs2,代碼行數:23,代碼來源:ssafile.py

示例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) 
開發者ID:PyCQA,項目名稱:bandit,代碼行數:18,代碼來源:utils.py

示例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 
開發者ID:dagster-io,項目名稱:dagster,代碼行數:21,代碼來源:fake_blob_client.py

示例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) 
開發者ID:viralogic,項目名稱:py-enumerable,代碼行數:18,代碼來源:core.py

示例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() 
開發者ID:Autodesk,項目名稱:molecular-design-toolkit,代碼行數:26,代碼來源:parmed_interface.py

示例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) 
開發者ID:windelbouwman,項目名稱:ppci,代碼行數:20,代碼來源:builder.py

示例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 
開發者ID:windelbouwman,項目名稱:ppci,代碼行數:19,代碼來源:api.py

示例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)) 
開發者ID:synthetichealth,項目名稱:syntheticmass,代碼行數:18,代碼來源:test_copy.py

示例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) 
開發者ID:maas,項目名稱:maas,代碼行數:19,代碼來源:avahi.py

示例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 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:21,代碼來源:util.py

示例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) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:38,代碼來源:saxutils.py

示例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() 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:42,代碼來源:event.py

示例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) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:17,代碼來源:backend_svg.py


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