Package PyFoam :: Package Basics :: Module LineReader
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Basics.LineReader

 1  #  ICE Revision: $Id$ 
 2  """Read a file line by line""" 
 3   
 4  from PyFoam.Infrastructure.Logging import foamLogger 
 5  from PyFoam.ThirdParty.six import print_ 
 6   
 7  import sys 
 8   
 9  from PyFoam.ThirdParty.six import PY3 
10   
11 -class LineReader(object):
12 """Read a line from a file 13 14 The line is stripped of whitespaces at the start and the end of 15 the line and stored in a variable self.line""" 16
17 - def __init__(self,stripAllSpaces=True):
18 """@param stripAllSpaces: remove all spaces from the line (instead of 19 only those on the left side)""" 20 self.stripAll=stripAllSpaces 21 self.line="" 22 self.goOn=True 23 self.wasInterupted=False 24 self.bytes=0
25
26 - def bytesRead(self):
27 """@return: number of bytes that were already read""" 28 return self.bytes
29
30 - def userSaidStop(self):
31 """@return: whether the reader caught a Keyboard-interrupt""" 32 return self.wasInterupted
33
34 - def read(self,fh):
35 """reads the next line 36 37 fh - filehandle to read from 38 39 Return value: False if the end of the file was reached. True 40 otherwise""" 41 42 if not self.goOn: 43 return False 44 45 try: 46 self.line=fh.readline() 47 if PY3: 48 if type(self.line) is bytes: 49 self.line=self.line.decode() 50 self.bytes+=len(self.line) 51 except KeyboardInterrupt: 52 e=sys.exc_info()[1] 53 foamLogger().warning("Keyboard Interrupt") 54 print_(" Interrupted by the Keyboard") 55 self.wasInterupted=True 56 self.goOn=False 57 self.line="" 58 return False 59 60 if len(self.line)>0: 61 status=True 62 else: 63 status=False 64 if self.stripAll: 65 self.line=self.line.strip() 66 else: 67 self.line=self.line.rstrip() 68 69 return status
70 71 # Should work with Python3 and Python2 72