StringIO.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. r"""File-like objects that read from or write to a string buffer.
  2. This implements (nearly) all stdio methods.
  3. f = StringIO() # ready for writing
  4. f = StringIO(buf) # ready for reading
  5. f.close() # explicitly release resources held
  6. flag = f.isatty() # always false
  7. pos = f.tell() # get current position
  8. f.seek(pos) # set current position
  9. f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
  10. buf = f.read() # read until EOF
  11. buf = f.read(n) # read up to n bytes
  12. buf = f.readline() # read until end of line ('\n') or EOF
  13. list = f.readlines()# list of f.readline() results until EOF
  14. f.truncate([size]) # truncate file at to at most size (default: current pos)
  15. f.write(buf) # write at current position
  16. f.writelines(list) # for line in list: f.write(line)
  17. f.getvalue() # return whole file's contents as a string
  18. Notes:
  19. - Using a real file is often faster (but less convenient).
  20. - There's also a much faster implementation in C, called cStringIO, but
  21. it's not subclassable.
  22. - fileno() is left unimplemented so that code which uses it triggers
  23. an exception early.
  24. - Seeking far beyond EOF and then writing will insert real null
  25. bytes that occupy space in the buffer.
  26. - There's a simple test set (see end of this file).
  27. """
  28. try:
  29. from errno import EINVAL
  30. except ImportError:
  31. EINVAL = 22
  32. __all__ = ["StringIO"]
  33. def _complain_ifclosed(closed):
  34. if closed:
  35. raise ValueError, "I/O operation on closed file"
  36. class StringIO:
  37. """class StringIO([buffer])
  38. When a StringIO object is created, it can be initialized to an existing
  39. string by passing the string to the constructor. If no string is given,
  40. the StringIO will start empty.
  41. The StringIO object can accept either Unicode or 8-bit strings, but
  42. mixing the two may take some care. If both are used, 8-bit strings that
  43. cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause
  44. a UnicodeError to be raised when getvalue() is called.
  45. """
  46. def __init__(self, buf = ''):
  47. # Force self.buf to be a string or unicode
  48. if not isinstance(buf, basestring):
  49. buf = str(buf)
  50. self.buf = buf
  51. self.len = len(buf)
  52. self.buflist = []
  53. self.pos = 0
  54. self.closed = False
  55. self.softspace = 0
  56. def __iter__(self):
  57. return self
  58. def next(self):
  59. """A file object is its own iterator, for example iter(f) returns f
  60. (unless f is closed). When a file is used as an iterator, typically
  61. in a for loop (for example, for line in f: print line), the next()
  62. method is called repeatedly. This method returns the next input line,
  63. or raises StopIteration when EOF is hit.
  64. """
  65. if self.closed:
  66. raise StopIteration
  67. r = self.readline()
  68. if not r:
  69. raise StopIteration
  70. return r
  71. def close(self):
  72. """Free the memory buffer.
  73. """
  74. if not self.closed:
  75. self.closed = True
  76. del self.buf, self.pos
  77. def isatty(self):
  78. """Returns False because StringIO objects are not connected to a
  79. tty-like device.
  80. """
  81. _complain_ifclosed(self.closed)
  82. return False
  83. def seek(self, pos, mode = 0):
  84. """Set the file's current position.
  85. The mode argument is optional and defaults to 0 (absolute file
  86. positioning); other values are 1 (seek relative to the current
  87. position) and 2 (seek relative to the file's end).
  88. There is no return value.
  89. """
  90. _complain_ifclosed(self.closed)
  91. if self.buflist:
  92. self.buf += ''.join(self.buflist)
  93. self.buflist = []
  94. if mode == 1:
  95. pos += self.pos
  96. elif mode == 2:
  97. pos += self.len
  98. self.pos = max(0, pos)
  99. def tell(self):
  100. """Return the file's current position."""
  101. _complain_ifclosed(self.closed)
  102. return self.pos
  103. def read(self, n = -1):
  104. """Read at most size bytes from the file
  105. (less if the read hits EOF before obtaining size bytes).
  106. If the size argument is negative or omitted, read all data until EOF
  107. is reached. The bytes are returned as a string object. An empty
  108. string is returned when EOF is encountered immediately.
  109. """
  110. _complain_ifclosed(self.closed)
  111. if self.buflist:
  112. self.buf += ''.join(self.buflist)
  113. self.buflist = []
  114. if n < 0:
  115. newpos = self.len
  116. else:
  117. newpos = min(self.pos+n, self.len)
  118. r = self.buf[self.pos:newpos]
  119. self.pos = newpos
  120. return r
  121. def readline(self, length=None):
  122. """Read one entire line from the file.
  123. A trailing newline character is kept in the string (but may be absent
  124. when a file ends with an incomplete line). If the size argument is
  125. present and non-negative, it is a maximum byte count (including the
  126. trailing newline) and an incomplete line may be returned.
  127. An empty string is returned only when EOF is encountered immediately.
  128. Note: Unlike stdio's fgets(), the returned string contains null
  129. characters ('\0') if they occurred in the input.
  130. """
  131. _complain_ifclosed(self.closed)
  132. if self.buflist:
  133. self.buf += ''.join(self.buflist)
  134. self.buflist = []
  135. i = self.buf.find('\n', self.pos)
  136. if i < 0:
  137. newpos = self.len
  138. else:
  139. newpos = i+1
  140. if length is not None:
  141. if self.pos + length < newpos:
  142. newpos = self.pos + length
  143. r = self.buf[self.pos:newpos]
  144. self.pos = newpos
  145. return r
  146. def readlines(self, sizehint = 0):
  147. """Read until EOF using readline() and return a list containing the
  148. lines thus read.
  149. If the optional sizehint argument is present, instead of reading up
  150. to EOF, whole lines totalling approximately sizehint bytes (or more
  151. to accommodate a final whole line).
  152. """
  153. total = 0
  154. lines = []
  155. line = self.readline()
  156. while line:
  157. lines.append(line)
  158. total += len(line)
  159. if 0 < sizehint <= total:
  160. break
  161. line = self.readline()
  162. return lines
  163. def truncate(self, size=None):
  164. """Truncate the file's size.
  165. If the optional size argument is present, the file is truncated to
  166. (at most) that size. The size defaults to the current position.
  167. The current file position is not changed unless the position
  168. is beyond the new file size.
  169. If the specified size exceeds the file's current size, the
  170. file remains unchanged.
  171. """
  172. _complain_ifclosed(self.closed)
  173. if size is None:
  174. size = self.pos
  175. elif size < 0:
  176. raise IOError(EINVAL, "Negative size not allowed")
  177. elif size < self.pos:
  178. self.pos = size
  179. self.buf = self.getvalue()[:size]
  180. self.len = size
  181. def write(self, s):
  182. """Write a string to the file.
  183. There is no return value.
  184. """
  185. _complain_ifclosed(self.closed)
  186. if not s: return
  187. # Force s to be a string or unicode
  188. if not isinstance(s, basestring):
  189. s = str(s)
  190. spos = self.pos
  191. slen = self.len
  192. if spos == slen:
  193. self.buflist.append(s)
  194. self.len = self.pos = spos + len(s)
  195. return
  196. if spos > slen:
  197. self.buflist.append('\0'*(spos - slen))
  198. slen = spos
  199. newpos = spos + len(s)
  200. if spos < slen:
  201. if self.buflist:
  202. self.buf += ''.join(self.buflist)
  203. self.buflist = [self.buf[:spos], s, self.buf[newpos:]]
  204. self.buf = ''
  205. if newpos > slen:
  206. slen = newpos
  207. else:
  208. self.buflist.append(s)
  209. slen = newpos
  210. self.len = slen
  211. self.pos = newpos
  212. def writelines(self, iterable):
  213. """Write a sequence of strings to the file. The sequence can be any
  214. iterable object producing strings, typically a list of strings. There
  215. is no return value.
  216. (The name is intended to match readlines(); writelines() does not add
  217. line separators.)
  218. """
  219. write = self.write
  220. for line in iterable:
  221. write(line)
  222. def flush(self):
  223. """Flush the internal buffer
  224. """
  225. _complain_ifclosed(self.closed)
  226. def getvalue(self):
  227. """
  228. Retrieve the entire contents of the "file" at any time before
  229. the StringIO object's close() method is called.
  230. The StringIO object can accept either Unicode or 8-bit strings,
  231. but mixing the two may take some care. If both are used, 8-bit
  232. strings that cannot be interpreted as 7-bit ASCII (that use the
  233. 8th bit) will cause a UnicodeError to be raised when getvalue()
  234. is called.
  235. """
  236. if self.buflist:
  237. self.buf += ''.join(self.buflist)
  238. self.buflist = []
  239. return self.buf
  240. # A little test suite
  241. def test():
  242. import sys
  243. if sys.argv[1:]:
  244. file = sys.argv[1]
  245. else:
  246. file = '/etc/passwd'
  247. lines = open(file, 'r').readlines()
  248. text = open(file, 'r').read()
  249. f = StringIO()
  250. for line in lines[:-2]:
  251. f.write(line)
  252. f.writelines(lines[-2:])
  253. if f.getvalue() != text:
  254. raise RuntimeError, 'write failed'
  255. length = f.tell()
  256. print 'File length =', length
  257. f.seek(len(lines[0]))
  258. f.write(lines[1])
  259. f.seek(0)
  260. print 'First line =', repr(f.readline())
  261. print 'Position =', f.tell()
  262. line = f.readline()
  263. print 'Second line =', repr(line)
  264. f.seek(-len(line), 1)
  265. line2 = f.read(len(line))
  266. if line != line2:
  267. raise RuntimeError, 'bad result after seek back'
  268. f.seek(len(line2), 1)
  269. list = f.readlines()
  270. line = list[-1]
  271. f.seek(f.tell() - len(line))
  272. line2 = f.read()
  273. if line != line2:
  274. raise RuntimeError, 'bad result after seek back from EOF'
  275. print 'Read', len(list), 'more lines'
  276. print 'File length =', f.tell()
  277. if f.tell() != length:
  278. raise RuntimeError, 'bad length'
  279. f.truncate(length/2)
  280. f.seek(0, 2)
  281. print 'Truncated length =', f.tell()
  282. if f.tell() != length/2:
  283. raise RuntimeError, 'truncate did not adjust length'
  284. f.close()
  285. if __name__ == '__main__':
  286. test()