Python io.TextIOBase() Examples

The following are 30 code examples for showing how to use io.TextIOBase(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module io , or try the search function .

Example 1
Project: Telethon   Author: LonamiWebs   File: utils.py    License: MIT License 6 votes vote down vote up
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) 
Example 2
Project: SplunkAdmins   Author: gjanders   File: event_writer.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 3
Project: pysubs2   Author: tkarabela   File: ssafile.py    License: MIT License 6 votes vote down vote up
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
    # ------------------------------------------------------------------------ 
Example 4
Project: bandit   Author: PyCQA   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 5
Project: dagster   Author: dagster-io   File: fake_blob_client.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 6
Project: py-enumerable   Author: viralogic   File: core.py    License: MIT License 6 votes vote down vote up
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) 
Example 7
Project: molecular-design-toolkit   Author: Autodesk   File: parmed_interface.py    License: Apache License 2.0 6 votes vote down vote up
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() 
Example 8
Project: ppci   Author: windelbouwman   File: builder.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example 9
Project: ppci   Author: windelbouwman   File: api.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example 10
Project: syntheticmass   Author: synthetichealth   File: test_copy.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 11
Project: bazarr   Author: morpheus65535   File: ssafile.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
    # ------------------------------------------------------------------------ 
Example 12
Project: maas   Author: maas   File: avahi.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 13
Project: Carnets   Author: holzschu   File: util.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 14
Project: jawfish   Author: war-and-code   File: saxutils.py    License: MIT License 5 votes vote down vote up
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) 
Example 15
Project: misp42splunk   Author: remg427   File: event.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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() 
Example 16
Project: misp42splunk   Author: remg427   File: event.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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() 
Example 17
Project: misp42splunk   Author: remg427   File: event.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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() 
Example 18
Project: Computable   Author: ktraunmueller   File: backend_svg.py    License: MIT License 5 votes vote down vote up
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) 
Example 19
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_svg.py    License: MIT License 5 votes vote down vote up
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) 
Example 20
Project: neural-network-animation   Author: miloharper   File: backend_svg.py    License: MIT License 5 votes vote down vote up
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 six.PY3:
                    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) 
Example 21
Project: SplunkAdmins   Author: gjanders   File: event.py    License: Apache License 2.0 5 votes vote down vote up
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() 
Example 22
Project: SplunkAdmins   Author: gjanders   File: event.py    License: Apache License 2.0 5 votes vote down vote up
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() 
Example 23
Project: prjxray   Author: SymbiFlow   File: xjson.py    License: ISC License 5 votes vote down vote up
def pprint(f, data):
    detach = False
    if not isinstance(f, io.TextIOBase):
        detach = True
        f = io.TextIOWrapper(f)
    data = sort(data)
    json.dump(data, f, indent=4)
    f.write('\n')
    f.flush()
    if detach:
        f.detach() 
Example 24
Project: armi   Author: terrapower   File: textProcessors.py    License: Apache License 2.0 5 votes vote down vote up
def _getRootFromSrc(
    src: Union[TextIO, pathlib.Path], root: Optional[pathlib.Path]
) -> pathlib.Path:
    if isinstance(src, pathlib.Path):
        root = root or src.parent.absolute()
    elif isinstance(src, io.TextIOBase):
        if root is None:
            raise ValueError("A stream was provided without a root directory.")
    else:
        raise TypeError("Unsupported source type: `{}`!".format(type(src)))

    return root 
Example 25
Project: pysubs2   Author: tkarabela   File: ssafile.py    License: MIT License 5 votes vote down vote up
def from_file(cls, fp, format_=None, fps=None, **kwargs):
        """
        Read subtitle file from file object.

        See :meth:`SSAFile.load()` for full description.

        Note:
            This is a low-level method. Usually, one of :meth:`SSAFile.load()`
            or :meth:`SSAFile.from_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).

        Returns:
            SSAFile

        """
        if format_ is None:
            # Autodetect subtitle format, then read again using correct parser.
            # The file might be a pipe and we need to read it twice,
            # so just buffer everything.
            text = fp.read()
            fragment = text[:10000]
            format_ = autodetect_format(fragment)
            fp = io.StringIO(text)

        impl = get_format_class(format_)
        subs = cls() # an empty subtitle file
        subs.format = format_
        subs.fps = fps
        impl.from_file(subs, fp, format_, fps=fps, **kwargs)
        return subs 
Example 26
Project: Fluid-Designer   Author: Microvellum   File: saxutils.py    License: GNU General Public License v3.0 5 votes vote down vote up
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

    if isinstance(out, (codecs.StreamWriter, codecs.StreamReaderWriter)):
        # use a codecs stream 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) 
Example 27
Project: Fluid-Designer   Author: Microvellum   File: test_pathlib.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_open_common(self):
        p = self.cls(BASE)
        with (p / 'fileA').open('r') as f:
            self.assertIsInstance(f, io.TextIOBase)
            self.assertEqual(f.read(), "this is file A\n")
        with (p / 'fileA').open('rb') as f:
            self.assertIsInstance(f, io.BufferedIOBase)
            self.assertEqual(f.read().strip(), b"this is file A")
        with (p / 'fileA').open('rb', buffering=0) as f:
            self.assertIsInstance(f, io.RawIOBase)
            self.assertEqual(f.read().strip(), b"this is file A") 
Example 28
Project: Fluid-Designer   Author: Microvellum   File: test_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_misc(self):
        shell = MockShell()
        f = PseudoOutputFile(shell, 'stdout', 'utf-8')
        self.assertIsInstance(f, io.TextIOBase)
        self.assertEqual(f.encoding, 'utf-8')
        self.assertIsNone(f.errors)
        self.assertIsNone(f.newlines)
        self.assertEqual(f.name, '<stdout>')
        self.assertFalse(f.closed)
        self.assertTrue(f.isatty())
        self.assertFalse(f.readable())
        self.assertTrue(f.writable())
        self.assertFalse(f.seekable()) 
Example 29
Project: Fluid-Designer   Author: Microvellum   File: test_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_misc(self):
        shell = MockShell()
        f = PseudoInputFile(shell, 'stdin', 'utf-8')
        self.assertIsInstance(f, io.TextIOBase)
        self.assertEqual(f.encoding, 'utf-8')
        self.assertIsNone(f.errors)
        self.assertIsNone(f.newlines)
        self.assertEqual(f.name, '<stdin>')
        self.assertFalse(f.closed)
        self.assertTrue(f.isatty())
        self.assertTrue(f.readable())
        self.assertFalse(f.writable())
        self.assertFalse(f.seekable()) 
Example 30
Project: Imogen   Author: CedricGuillemet   File: client.py    License: MIT License 5 votes vote down vote up
def _is_textIO(stream):
        """Test whether a file-like object is a text or a binary stream.
        """
        return isinstance(stream, io.TextIOBase)