home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / dos-8x3 / arrayio.py next >
Encoding:
Python Source  |  1996-07-22  |  3.7 KB  |  143 lines

  1. """File-like objects that read/write an array buffer.
  2.  
  3. This implements (nearly) all stdio methods.
  4.  
  5. f = ArrayIO()       # ready for writing
  6. f = ArrayIO(buf)    # ready for reading
  7. f.close()           # explicitly release resources held
  8. flag = f.isatty()   # always false
  9. pos = f.tell()      # get current position
  10. f.seek(pos)         # set current position
  11. f.seek(pos, mode)   # mode 0: absolute; 1: relative; 2: relative to EOF
  12. buf = f.read()      # read until EOF
  13. buf = f.read(n)     # read up to n bytes
  14. buf = f.readline()  # read until end of line ('\n') or EOF
  15. list = f.readlines()# list of f.readline() results until EOF
  16. f.write(buf)        # write at current position
  17. f.writelines(list)  # for line in list: f.write(line)
  18. f.getvalue()        # return whole file's contents as a string
  19.  
  20. Notes:
  21. - This is very similar to StringIO.  StringIO is faster for reading,
  22.   but ArrayIO is faster for writing.
  23. - ArrayIO uses an array object internally, but all its interfaces
  24.   accept and return strings.
  25. - Using a real file is often faster (but less convenient).
  26. - fileno() is left unimplemented so that code which uses it triggers
  27.   an exception early.
  28. - Seeking far beyond EOF and then writing will insert real null
  29.   bytes that occupy space in the buffer.
  30. - There's a simple test set (see end of this file).
  31. """
  32.  
  33. import string
  34. from array import array
  35.  
  36. class ArrayIO:
  37.     def __init__(self, buf = ''):
  38.         self.buf = array('c', buf)
  39.         self.pos = 0
  40.         self.closed = 0
  41.         self.softspace = 0
  42.     def close(self):
  43.         if not self.closed:
  44.             self.closed = 1
  45.             del self.buf, self.pos
  46.     def isatty(self):
  47.         return 0
  48.     def seek(self, pos, mode = 0):
  49.         if mode == 1:
  50.             pos = pos + self.pos
  51.         elif mode == 2:
  52.             pos = pos + len(self.buf)
  53.         self.pos = max(0, pos)
  54.     def tell(self):
  55.         return self.pos
  56.     def read(self, n = -1):
  57.         if n < 0:
  58.             newpos = len(self.buf)
  59.         else:
  60.             newpos = min(self.pos+n, len(self.buf))
  61.         r = self.buf[self.pos:newpos].tostring()
  62.         self.pos = newpos
  63.         return r
  64.     def readline(self):
  65.         i = string.find(self.buf[self.pos:].tostring(), '\n')
  66.         if i < 0:
  67.             newpos = len(self.buf)
  68.         else:
  69.             newpos = self.pos+i+1
  70.         r = self.buf[self.pos:newpos].tostring()
  71.         self.pos = newpos
  72.         return r
  73.     def readlines(self):
  74.         lines = string.splitfields(self.read(), '\n')
  75.         if not lines:
  76.             return lines
  77.         for i in range(len(lines)-1):
  78.             lines[i] = lines[i] + '\n'
  79.         if not lines[-1]:
  80.             del lines[-1]
  81.         return lines
  82.     def write(self, s):
  83.         if not s: return
  84.         a = array('c', s)
  85.         n = self.pos - len(self.buf)
  86.         if n > 0:
  87.             self.buf[len(self.buf):] = array('c', '\0')*n
  88.         newpos = self.pos + len(a)
  89.         self.buf[self.pos:newpos] = a
  90.         self.pos = newpos
  91.     def writelines(self, list):
  92.         self.write(string.joinfields(list, ''))
  93.     def flush(self):
  94.         pass
  95.     def getvalue(self):
  96.         return self.buf.tostring()
  97.  
  98.  
  99. # A little test suite
  100.  
  101. def test():
  102.     import sys
  103.     if sys.argv[1:]:
  104.         file = sys.argv[1]
  105.     else:
  106.         file = '/etc/passwd'
  107.     lines = open(file, 'r').readlines()
  108.     text = open(file, 'r').read()
  109.     f = ArrayIO()
  110.     for line in lines[:-2]:
  111.         f.write(line)
  112.     f.writelines(lines[-2:])
  113.     if f.getvalue() != text:
  114.         raise RuntimeError, 'write failed'
  115.     length = f.tell()
  116.     print 'File length =', length
  117.     f.seek(len(lines[0]))
  118.     f.write(lines[1])
  119.     f.seek(0)
  120.     print 'First line =', `f.readline()`
  121.     here = f.tell()
  122.     line = f.readline()
  123.     print 'Second line =', `line`
  124.     f.seek(-len(line), 1)
  125.     line2 = f.read(len(line))
  126.     if line != line2:
  127.         raise RuntimeError, 'bad result after seek back'
  128.     f.seek(len(line2), 1)
  129.     list = f.readlines()
  130.     line = list[-1]
  131.     f.seek(f.tell() - len(line))
  132.     line2 = f.read()
  133.     if line != line2:
  134.         raise RuntimeError, 'bad result after seek back from EOF'
  135.     print 'Read', len(list), 'more lines'
  136.     print 'File length =', f.tell()
  137.     if f.tell() != length:
  138.         raise RuntimeError, 'bad length'
  139.     f.close()
  140.  
  141. if __name__ == '__main__':
  142.     test()
  143.