+++ /dev/null
-r"""File-like objects that read from or write to a string buffer.\r
-\r
-This implements (nearly) all stdio methods.\r
-\r
-f = StringIO() # ready for writing\r
-f = StringIO(buf) # ready for reading\r
-f.close() # explicitly release resources held\r
-flag = f.isatty() # always false\r
-pos = f.tell() # get current position\r
-f.seek(pos) # set current position\r
-f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF\r
-buf = f.read() # read until EOF\r
-buf = f.read(n) # read up to n bytes\r
-buf = f.readline() # read until end of line ('\n') or EOF\r
-list = f.readlines()# list of f.readline() results until EOF\r
-f.truncate([size]) # truncate file at to at most size (default: current pos)\r
-f.write(buf) # write at current position\r
-f.writelines(list) # for line in list: f.write(line)\r
-f.getvalue() # return whole file's contents as a string\r
-\r
-Notes:\r
-- Using a real file is often faster (but less convenient).\r
-- There's also a much faster implementation in C, called cStringIO, but\r
- it's not subclassable.\r
-- fileno() is left unimplemented so that code which uses it triggers\r
- an exception early.\r
-- Seeking far beyond EOF and then writing will insert real null\r
- bytes that occupy space in the buffer.\r
-- There's a simple test set (see end of this file).\r
-"""\r
-try:\r
- from errno import EINVAL\r
-except ImportError:\r
- EINVAL = 22\r
-\r
-__all__ = ["StringIO"]\r
-\r
-def _complain_ifclosed(closed):\r
- if closed:\r
- raise ValueError, "I/O operation on closed file"\r
-\r
-class StringIO:\r
- """class StringIO([buffer])\r
-\r
- When a StringIO object is created, it can be initialized to an existing\r
- string by passing the string to the constructor. If no string is given,\r
- the StringIO will start empty.\r
-\r
- The StringIO object can accept either Unicode or 8-bit strings, but\r
- mixing the two may take some care. If both are used, 8-bit strings that\r
- cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause\r
- a UnicodeError to be raised when getvalue() is called.\r
- """\r
- def __init__(self, buf = ''):\r
- # Force self.buf to be a string or unicode\r
- if not isinstance(buf, basestring):\r
- buf = str(buf)\r
- self.buf = buf\r
- self.len = len(buf)\r
- self.buflist = []\r
- self.pos = 0\r
- self.closed = False\r
- self.softspace = 0\r
-\r
- def __iter__(self):\r
- return self\r
-\r
- def next(self):\r
- """A file object is its own iterator, for example iter(f) returns f\r
- (unless f is closed). When a file is used as an iterator, typically\r
- in a for loop (for example, for line in f: print line), the next()\r
- method is called repeatedly. This method returns the next input line,\r
- or raises StopIteration when EOF is hit.\r
- """\r
- _complain_ifclosed(self.closed)\r
- r = self.readline()\r
- if not r:\r
- raise StopIteration\r
- return r\r
-\r
- def close(self):\r
- """Free the memory buffer.\r
- """\r
- if not self.closed:\r
- self.closed = True\r
- del self.buf, self.pos\r
-\r
- def isatty(self):\r
- """Returns False because StringIO objects are not connected to a\r
- tty-like device.\r
- """\r
- _complain_ifclosed(self.closed)\r
- return False\r
-\r
- def seek(self, pos, mode = 0):\r
- """Set the file's current position.\r
-\r
- The mode argument is optional and defaults to 0 (absolute file\r
- positioning); other values are 1 (seek relative to the current\r
- position) and 2 (seek relative to the file's end).\r
-\r
- There is no return value.\r
- """\r
- _complain_ifclosed(self.closed)\r
- if self.buflist:\r
- self.buf += ''.join(self.buflist)\r
- self.buflist = []\r
- if mode == 1:\r
- pos += self.pos\r
- elif mode == 2:\r
- pos += self.len\r
- self.pos = max(0, pos)\r
-\r
- def tell(self):\r
- """Return the file's current position."""\r
- _complain_ifclosed(self.closed)\r
- return self.pos\r
-\r
- def read(self, n = -1):\r
- """Read at most size bytes from the file\r
- (less if the read hits EOF before obtaining size bytes).\r
-\r
- If the size argument is negative or omitted, read all data until EOF\r
- is reached. The bytes are returned as a string object. An empty\r
- string is returned when EOF is encountered immediately.\r
- """\r
- _complain_ifclosed(self.closed)\r
- if self.buflist:\r
- self.buf += ''.join(self.buflist)\r
- self.buflist = []\r
- if n is None or n < 0:\r
- newpos = self.len\r
- else:\r
- newpos = min(self.pos+n, self.len)\r
- r = self.buf[self.pos:newpos]\r
- self.pos = newpos\r
- return r\r
-\r
- def readline(self, length=None):\r
- r"""Read one entire line from the file.\r
-\r
- A trailing newline character is kept in the string (but may be absent\r
- when a file ends with an incomplete line). If the size argument is\r
- present and non-negative, it is a maximum byte count (including the\r
- trailing newline) and an incomplete line may be returned.\r
-\r
- An empty string is returned only when EOF is encountered immediately.\r
-\r
- Note: Unlike stdio's fgets(), the returned string contains null\r
- characters ('\0') if they occurred in the input.\r
- """\r
- _complain_ifclosed(self.closed)\r
- if self.buflist:\r
- self.buf += ''.join(self.buflist)\r
- self.buflist = []\r
- i = self.buf.find('\n', self.pos)\r
- if i < 0:\r
- newpos = self.len\r
- else:\r
- newpos = i+1\r
- if length is not None and length > 0:\r
- if self.pos + length < newpos:\r
- newpos = self.pos + length\r
- r = self.buf[self.pos:newpos]\r
- self.pos = newpos\r
- return r\r
-\r
- def readlines(self, sizehint = 0):\r
- """Read until EOF using readline() and return a list containing the\r
- lines thus read.\r
-\r
- If the optional sizehint argument is present, instead of reading up\r
- to EOF, whole lines totalling approximately sizehint bytes (or more\r
- to accommodate a final whole line).\r
- """\r
- total = 0\r
- lines = []\r
- line = self.readline()\r
- while line:\r
- lines.append(line)\r
- total += len(line)\r
- if 0 < sizehint <= total:\r
- break\r
- line = self.readline()\r
- return lines\r
-\r
- def truncate(self, size=None):\r
- """Truncate the file's size.\r
-\r
- If the optional size argument is present, the file is truncated to\r
- (at most) that size. The size defaults to the current position.\r
- The current file position is not changed unless the position\r
- is beyond the new file size.\r
-\r
- If the specified size exceeds the file's current size, the\r
- file remains unchanged.\r
- """\r
- _complain_ifclosed(self.closed)\r
- if size is None:\r
- size = self.pos\r
- elif size < 0:\r
- raise IOError(EINVAL, "Negative size not allowed")\r
- elif size < self.pos:\r
- self.pos = size\r
- self.buf = self.getvalue()[:size]\r
- self.len = size\r
-\r
- def write(self, s):\r
- """Write a string to the file.\r
-\r
- There is no return value.\r
- """\r
- _complain_ifclosed(self.closed)\r
- if not s: return\r
- # Force s to be a string or unicode\r
- if not isinstance(s, basestring):\r
- s = str(s)\r
- spos = self.pos\r
- slen = self.len\r
- if spos == slen:\r
- self.buflist.append(s)\r
- self.len = self.pos = spos + len(s)\r
- return\r
- if spos > slen:\r
- self.buflist.append('\0'*(spos - slen))\r
- slen = spos\r
- newpos = spos + len(s)\r
- if spos < slen:\r
- if self.buflist:\r
- self.buf += ''.join(self.buflist)\r
- self.buflist = [self.buf[:spos], s, self.buf[newpos:]]\r
- self.buf = ''\r
- if newpos > slen:\r
- slen = newpos\r
- else:\r
- self.buflist.append(s)\r
- slen = newpos\r
- self.len = slen\r
- self.pos = newpos\r
-\r
- def writelines(self, iterable):\r
- """Write a sequence of strings to the file. The sequence can be any\r
- iterable object producing strings, typically a list of strings. There\r
- is no return value.\r
-\r
- (The name is intended to match readlines(); writelines() does not add\r
- line separators.)\r
- """\r
- write = self.write\r
- for line in iterable:\r
- write(line)\r
-\r
- def flush(self):\r
- """Flush the internal buffer\r
- """\r
- _complain_ifclosed(self.closed)\r
-\r
- def getvalue(self):\r
- """\r
- Retrieve the entire contents of the "file" at any time before\r
- the StringIO object's close() method is called.\r
-\r
- The StringIO object can accept either Unicode or 8-bit strings,\r
- but mixing the two may take some care. If both are used, 8-bit\r
- strings that cannot be interpreted as 7-bit ASCII (that use the\r
- 8th bit) will cause a UnicodeError to be raised when getvalue()\r
- is called.\r
- """\r
- _complain_ifclosed(self.closed)\r
- if self.buflist:\r
- self.buf += ''.join(self.buflist)\r
- self.buflist = []\r
- return self.buf\r
-\r
-\r
-# A little test suite\r
-\r
-def test():\r
- import sys\r
- if sys.argv[1:]:\r
- file = sys.argv[1]\r
- else:\r
- file = '/etc/passwd'\r
- lines = open(file, 'r').readlines()\r
- text = open(file, 'r').read()\r
- f = StringIO()\r
- for line in lines[:-2]:\r
- f.write(line)\r
- f.writelines(lines[-2:])\r
- if f.getvalue() != text:\r
- raise RuntimeError, 'write failed'\r
- length = f.tell()\r
- print 'File length =', length\r
- f.seek(len(lines[0]))\r
- f.write(lines[1])\r
- f.seek(0)\r
- print 'First line =', repr(f.readline())\r
- print 'Position =', f.tell()\r
- line = f.readline()\r
- print 'Second line =', repr(line)\r
- f.seek(-len(line), 1)\r
- line2 = f.read(len(line))\r
- if line != line2:\r
- raise RuntimeError, 'bad result after seek back'\r
- f.seek(len(line2), 1)\r
- list = f.readlines()\r
- line = list[-1]\r
- f.seek(f.tell() - len(line))\r
- line2 = f.read()\r
- if line != line2:\r
- raise RuntimeError, 'bad result after seek back from EOF'\r
- print 'Read', len(list), 'more lines'\r
- print 'File length =', f.tell()\r
- if f.tell() != length:\r
- raise RuntimeError, 'bad length'\r
- f.truncate(length/2)\r
- f.seek(0, 2)\r
- print 'Truncated length =', f.tell()\r
- if f.tell() != length/2:\r
- raise RuntimeError, 'truncate did not adjust length'\r
- f.close()\r
-\r
-if __name__ == '__main__':\r
- test()\r