Reads a file-like buffer object into lines and optionally prints the output.
13704
def read_buffer(io, print_output=False, print_func=None):
    '''
    
    '''

    # TODO: research this further - some steps towards handling stdin (ie password requests
    # from programs that don't notice there's no TTY to accept passwords from!). This just
    # prints output as below, but stores partial lines in a buffer, which could be printed
    # when ready to accept input. Or detected and raise an error.

    # GitHub issue: https://github.com/Fizzadar/pyinfra/issues/40

    # buff = ''
    # data = io.read(1)

    # while data:
    #     # Append to the buffer
    #     buff += data

    #     # Newlines in the buffer? Break them out
    #     if '\n' in buff:
    #         lines = buff.split('\n')

    #         # Set the buffer back to just the last line
    #         buff = lines[-1]

    #         # Get the other lines, strip them
    #         lines = [
    #             line.strip()
    #             for line in lines[:-1]
    #         ]

    #         out.extend(lines)

    #         for line in lines:
    #             _print(line)

    #     # Get next data
    #     data = io.read(1)

    # if buff:
    #     line = buff.strip()
    #     out.append(line)
    #     _print(line)

    def _print(line):
        if print_output:
            if print_func:
                formatted_line = print_func(line)
            else:
                formatted_line = line
            encoded_line = unicode(formatted_line).encode('utf-8')
            print(encoded_line)

    out = []

    for line in io:
        # Handle local Popen shells returning list of bytes, not strings
        if not isinstance(line, six.text_type):
            line = line.decode('utf-8')

        line = line.strip()
        out.append(line)

        _print(line)

    return out
576854
def write(self, b: bytes) -> None:
        """"""
        if not isinstance(b, bytes):
            raise TypeError('a bytes-like object is required, not {}'.format(type(b)))
        if not self.std_sim_instance.pause_storage:
            self.byte_buf += b
        if self.std_sim_instance.echo:
            self.std_sim_instance.inner_stream.buffer.write(b)

            # Since StdSim wraps TextIO streams, we will flush the stream if line buffering is on
            # and the bytes being written contain a new line character. This is helpful when StdSim
            # is being used to capture output of a shell command because it causes the output to print
            # to the screen more often than if we waited for the stream to flush its buffer.
            if self.std_sim_instance.line_buffering:
                if any(newline in b for newline in ByteBuf.NEWLINES):
                    self.std_sim_instance.flush()
488411
def SkipAhead(self, file_object, number_of_characters):
    
    lines_size = len(self.lines)
    while number_of_characters >= lines_size:
      number_of_characters -= lines_size

      self.lines = ''
      self.ReadLines(file_object)
      lines_size = len(self.lines)
      if lines_size == 0:
        return

    self.lines = self.lines[number_of_characters:]
942459
def stream_stdin_lines():
    """"""
    stdin = os.fdopen(sys.stdin.fileno(), 'r', 0)
    while True:
        line = stdin.readline()
        if line:
            yield line
        else:
            break
268322
def read_line(self):
        
        buf = b''
        while not self.eof and buf.endswith(b'\n') is False:
            buf += yield from self.read_byte()

        if self.eof:
            buf = b''

        # Remove \n character
        buf = buf.replace(b'\n', b'')

        return buf
1041584
def load_ply(fileobj):
    """"""
    def nextline():
        """Read next line, skip comments"""
        while True:
            line = fileobj.readline()
            assert line != ''  # eof
            if not line.startswith('comment'):
                return line.strip()

    assert nextline() == 'ply'
    assert nextline() == 'format ascii 1.0'
    line = nextline()
    assert line.startswith('element vertex')
    nverts = int(line.split()[2])
    # print 'nverts : ', nverts
    assert nextline() == 'property float x'
    assert nextline() == 'property float y'
    assert nextline() == 'property float z'
    line = nextline()

    assert line.startswith('element face')
    nfaces = int(line.split()[2])
    # print 'nfaces : ', nfaces
    assert nextline() == 'property list uchar int vertex_indices'
    line = nextline()
    has_texcoords = line == 'property list uchar float texcoord'
    if has_texcoords:
        assert nextline() == 'end_header'
    else:
        assert line == 'end_header'

    # Verts
    verts = np.zeros((nverts, 3))
    for i in range(nverts):
        vals = nextline().split()
        verts[i, :] = [float(v) for v in vals[:3]]
    # Faces
    faces = []
    faces_uv = []
    for i in range(nfaces):
        vals = nextline().split()
        assert int(vals[0]) == 3
        faces.append([int(v) for v in vals[1:4]])
        if has_texcoords:
            assert len(vals) == 11
            assert int(vals[4]) == 6
            faces_uv.append([(float(vals[5]), float(vals[6])),
                             (float(vals[7]), float(vals[8])),
                             (float(vals[9]), float(vals[10]))])
            # faces_uv.append([float(v) for v in vals[5:]])
        else:
            assert len(vals) == 4
    return verts, faces, faces_uv
1227077
def readline( file, skip_blank=False ):
    """"""
    while 1:
        line = file.readline()
        #print "every line: %r" % line
        if not line: return None 
        if line[0] != '#' and not ( skip_blank and line.isspace() ):
            return line
955384
def readlines(self):
        """"""
        if self.grammar:
            tot = []
            # Used this way instead of a 'for' loop against
            # self.file.readlines() so that there wasn't two copies of the file
            # in memory.
            while 1:
                line = self.file.readline()
                if not line:
                    break
                tot.append(line)
            return tot
        return self.file.readlines()
637027
def buffered_read(fh, lock, offsets, bytecounts, buffersize=None):
    """"""
    if buffersize is None:
        buffersize = 2**26
    length = len(offsets)
    i = 0
    while i < length:
        data = []
        with lock:
            size = 0
            while size < buffersize and i < length:
                fh.seek(offsets[i])
                bytecount = bytecounts[i]
                data.append(fh.read(bytecount))
                # buffer = bytearray(bytecount)
                # n = fh.readinto(buffer)
                # data.append(buffer[:n])
                size += bytecount
                i += 1
        for segment in data:
            yield segment
128883
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
        JavaFileObject outFile
            = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
                                               cdef.sym.flatname.toString(),
                                               JavaFileObject.Kind.SOURCE,
                                               null);
        if (inputFiles.contains(outFile)) {
            log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
            return null;
        } else {
            BufferedWriter out = new BufferedWriter(outFile.openWriter());
            try {
                new Pretty(out, true).printUnit(env.toplevel, cdef);
                if (verbose)
                    log.printVerbose("wrote.file", outFile);
            } finally {
                out.close();
            }
            return outFile;
        }
    }
361658
protected void writeFileTop(OutputStream o) throws Util.Exit {
        PrintWriter pw = wrapWriter(o);
        pw.println("/* DO NOT EDIT THIS FILE - it is machine generated */" + lineSep +
                   getIncludes());
    }
127996
def output(file_like_object, path, verbose=False):
    """"""
    if not path:
        for line in file_like_object:
            if verbose:
                print_info(line.rstrip())
            else:
                print(line.rstrip())
    else:
        try:
            object_file = open(os.path.expanduser(path), "w", encoding="utf-8")
            shutil.copyfileobj(file_like_object, object_file)
            object_file.close()
        except EnvironmentError as xxx_todo_changeme:
            (errno, strerror) = xxx_todo_changeme.args
            error_line_list = [
                "Could not write to object_file: {}".format(path),
                "I/O error({}): {}".format(errno, strerror),
            ]
            error_message = "\n".join(error_line_list)
            raise d1_cli.impl.exceptions.CLIError(error_message)
1131448
def read_file_to_buffer(filename):
    
    f = open(filename, "r")
    buf = BytesIO(f.read())
    f.close()
    return buf
195146
def readlines(self, offset=0):
        """"""
        try:
            with open(self._filepath) as fp:
                # For full read go through existing lines in file
                if self._full_read:
                    fp.seek(offset)
                    for row in fp:
                        yield row

                # Okay now dynamically tail the file
                if self._tail:
                    while True:
                        current = fp.tell()
                        row = fp.readline()
                        if row:
                            yield row
                        else:
                            fp.seek(current)
                            time.sleep(self._sleep)

        except IOError as err:
            print('Error reading the file {0}: {1}'.format(self._filepath, err))
            return
587697
def _print_lines(self, lines, start, breaks=(), frame=None):
        """"""
        if frame:
            current_lineno = frame.f_lineno
            exc_lineno = self.tb_lineno.get(frame, -1)
        else:
            current_lineno = exc_lineno = -1
        for lineno, line in enumerate(lines, start):
            s = str(lineno).rjust(3)
            if len(s) < 4:
                s += ' '
            if lineno in breaks:
                s += 'B'
            else:
                s += ' '
            if lineno == current_lineno:
                s += '->'
            elif lineno == exc_lineno:
                s += '>>'
            self.message(s + '\t' + line.rstrip())
944246
def _py_read1(fileObj, maxBuffer):
    '''
        
    '''
    i = 0
    ret = []
    while i < maxBuffer:
        c = fileObj.read(1)
        if c == '':
            # Stream has been closed
            break
        i += 1
        ret.append(c)
        # Use a very low timeout so we only grab more data if it's immediately available.
        (readyToRead, junk1, junk2) = select.select([fileObj], [], [], .00001)
        if not readyToRead:
            break

    return ''.join(ret)
926040
function BufferStreamReader (data, options) {
  if (!(this instanceof BufferStreamReader)) {
    return new BufferStreamReader(data);
  }

  if (!options) {
    options = {};
  }

  stream.Readable.call(this, options);

  this._data = null;
  this._chunkSize = options.chunkSize || -1;

  if (typeof data === 'string') {
    this._data = new Buffer(data, options.encoding || 'utf8');
  } else if (Buffer.isBuffer(data)) {
    this._data = data;
  }
}