PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/StringIO.py

http://github.com/IronLanguages/main
Python | 324 lines | 309 code | 2 blank | 13 comment | 3 complexity | 71686dbb69a0544ed2b4d6f5e68b069f MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  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. _complain_ifclosed(self.closed)
  66. r = self.readline()
  67. if not r:
  68. raise StopIteration
  69. return r
  70. def close(self):
  71. """Free the memory buffer.
  72. """
  73. if not self.closed:
  74. self.closed = True
  75. del self.buf, self.pos
  76. def isatty(self):
  77. """Returns False because StringIO objects are not connected to a
  78. tty-like device.
  79. """
  80. _complain_ifclosed(self.closed)
  81. return False
  82. def seek(self, pos, mode = 0):
  83. """Set the file's current position.
  84. The mode argument is optional and defaults to 0 (absolute file
  85. positioning); other values are 1 (seek relative to the current
  86. position) and 2 (seek relative to the file's end).
  87. There is no return value.
  88. """
  89. _complain_ifclosed(self.closed)
  90. if self.buflist:
  91. self.buf += ''.join(self.buflist)
  92. self.buflist = []
  93. if mode == 1:
  94. pos += self.pos
  95. elif mode == 2:
  96. pos += self.len
  97. self.pos = max(0, pos)
  98. def tell(self):
  99. """Return the file's current position."""
  100. _complain_ifclosed(self.closed)
  101. return self.pos
  102. def read(self, n = -1):
  103. """Read at most size bytes from the file
  104. (less if the read hits EOF before obtaining size bytes).
  105. If the size argument is negative or omitted, read all data until EOF
  106. is reached. The bytes are returned as a string object. An empty
  107. string is returned when EOF is encountered immediately.
  108. """
  109. _complain_ifclosed(self.closed)
  110. if self.buflist:
  111. self.buf += ''.join(self.buflist)
  112. self.buflist = []
  113. if n is None or n < 0:
  114. newpos = self.len
  115. else:
  116. newpos = min(self.pos+n, self.len)
  117. r = self.buf[self.pos:newpos]
  118. self.pos = newpos
  119. return r
  120. def readline(self, length=None):
  121. r"""Read one entire line from the file.
  122. A trailing newline character is kept in the string (but may be absent
  123. when a file ends with an incomplete line). If the size argument is
  124. present and non-negative, it is a maximum byte count (including the
  125. trailing newline) and an incomplete line may be returned.
  126. An empty string is returned only when EOF is encountered immediately.
  127. Note: Unlike stdio's fgets(), the returned string contains null
  128. characters ('\0') if they occurred in the input.
  129. """
  130. _complain_ifclosed(self.closed)
  131. if self.buflist:
  132. self.buf += ''.join(self.buflist)
  133. self.buflist = []
  134. i = self.buf.find('\n', self.pos)
  135. if i < 0:
  136. newpos = self.len
  137. else:
  138. newpos = i+1
  139. if length is not None and length > 0:
  140. if self.pos + length < newpos:
  141. newpos = self.pos + length
  142. r = self.buf[self.pos:newpos]
  143. self.pos = newpos
  144. return r
  145. def readlines(self, sizehint = 0):
  146. """Read until EOF using readline() and return a list containing the
  147. lines thus read.
  148. If the optional sizehint argument is present, instead of reading up
  149. to EOF, whole lines totalling approximately sizehint bytes (or more
  150. to accommodate a final whole line).
  151. """
  152. total = 0
  153. lines = []
  154. line = self.readline()
  155. while line:
  156. lines.append(line)
  157. total += len(line)
  158. if 0 < sizehint <= total:
  159. break
  160. line = self.readline()
  161. return lines
  162. def truncate(self, size=None):
  163. """Truncate the file's size.
  164. If the optional size argument is present, the file is truncated to
  165. (at most) that size. The size defaults to the current position.
  166. The current file position is not changed unless the position
  167. is beyond the new file size.
  168. If the specified size exceeds the file's current size, the
  169. file remains unchanged.
  170. """
  171. _complain_ifclosed(self.closed)
  172. if size is None:
  173. size = self.pos
  174. elif size < 0:
  175. raise IOError(EINVAL, "Negative size not allowed")
  176. elif size < self.pos:
  177. self.pos = size
  178. self.buf = self.getvalue()[:size]
  179. self.len = size
  180. def write(self, s):
  181. """Write a string to the file.
  182. There is no return value.
  183. """
  184. _complain_ifclosed(self.closed)
  185. if not s: return
  186. # Force s to be a string or unicode
  187. if not isinstance(s, basestring):
  188. s = str(s)
  189. spos = self.pos
  190. slen = self.len
  191. if spos == slen:
  192. self.buflist.append(s)
  193. self.len = self.pos = spos + len(s)
  194. return
  195. if spos > slen:
  196. self.buflist.append('\0'*(spos - slen))
  197. slen = spos
  198. newpos = spos + len(s)
  199. if spos < slen:
  200. if self.buflist:
  201. self.buf += ''.join(self.buflist)
  202. self.buflist = [self.buf[:spos], s, self.buf[newpos:]]
  203. self.buf = ''
  204. if newpos > slen:
  205. slen = newpos
  206. else:
  207. self.buflist.append(s)
  208. slen = newpos
  209. self.len = slen
  210. self.pos = newpos
  211. def writelines(self, iterable):
  212. """Write a sequence of strings to the file. The sequence can be any
  213. iterable object producing strings, typically a list of strings. There
  214. is no return value.
  215. (The name is intended to match readlines(); writelines() does not add
  216. line separators.)
  217. """
  218. write = self.write
  219. for line in iterable:
  220. write(line)
  221. def flush(self):
  222. """Flush the internal buffer
  223. """
  224. _complain_ifclosed(self.closed)
  225. def getvalue(self):
  226. """
  227. Retrieve the entire contents of the "file" at any time before
  228. the StringIO object's close() method is called.
  229. The StringIO object can accept either Unicode or 8-bit strings,
  230. but mixing the two may take some care. If both are used, 8-bit
  231. strings that cannot be interpreted as 7-bit ASCII (that use the
  232. 8th bit) will cause a UnicodeError to be raised when getvalue()
  233. is called.
  234. """
  235. _complain_ifclosed(self.closed)
  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()