Ignore:
Timestamp:
Aug 4, 2013, 8:09:18 PM (6 years ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Message:
Use an implementation of `write` that doesn't need to call `flush` on
every `write` call.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • ftputil/file.py

    r1343 r1344  
    8686        self.raw.flush()
    8787
     88    # Derived from `socket.py` in Python 2.6 and 2.7.
     89    def _write_buffer_size(self):
     90        """Return current size of the write buffer in bytes."""
     91        if hasattr(self.raw, "_wbuf_len"):
     92            # Python 2.6.3 - 2.7.5
     93            return self.raw._wbuf_len
     94        elif hasattr(self.raw, "_get_wbuf_len"):
     95            # Python 2.6 - 2.6.2. (Strictly speaking, all other
     96            # Python 2.6 versions have a `_get_wbuf_len` method, but
     97            # for 2.6.3 and up it returns `_wbuf_len`).
     98            return self.raw._get_wbuf_len()
     99        else:
     100            # Fallback. In the context of `write` this means the file
     101            # appears to be unbuffered.
     102            return 0
     103
    88104    def write(self, bytes_or_bytearray):
    89105        # `BufferedWriter.write` has to return the number of written
    90         # bytes. Since we don't really know how many bytes got
    91         # actually written, return the length of the full data, but
    92         # also call `flush` to increase the chance that all bytes are
    93         # written.
     106        # bytes, but files returned from `socket.makefile` in Python 2
     107        # return `None`. Hence provide a workaround.
     108        old_buffer_byte_count = self._write_buffer_size()
     109        added_byte_count = len(bytes_or_bytearray)
    94110        self.raw.write(bytes_or_bytearray)
    95         # TODO: Measure impact of flushing for many small writes.
    96         self.flush()
    97         return len(bytes_or_bytearray)
     111        new_buffer_byte_count = self._write_buffer_size()
     112        return (old_buffer_byte_count + added_byte_count -
     113                new_buffer_byte_count)
    98114
    99115    def writelines(self, lines):
Note: See TracChangeset for help on using the changeset viewer.