"""
ReportWithLevels
__author__ = 'Margery Harrison'
__license__ = "Public Domain"
__version__ = "1.0"
"""
import sys
class ReportWithLevels():
def __init__(self):
"""
Sets the default values for the class
"""
self.fdout=sys.stdout #default - writes report to stdout
self.number_width=10
self.level_indent=2
self.total_width=30
self.debug = True
self.min_level = 1
self.max_level = 4
#levels before which to print a newline
self.newline_before = [1]
# open the input path as file to write to
def open_outfile(self,path):
try:
self.fdout = open(path,'w')
except IOError:
msg="{0:s} Can't open and write to {1:s}".format(self.__class__.__name__,path)
sys.stderr.write(msg)
# print debug statement if debugging turned on
def debugPrint(self,message):
if self.debug:
print(message)
# Write a line out to the output file with newline at end
def writeLine(self,message):
self.fdout.write(message + '\n')
# Print message and total with indentation set by input level
def printLevel(self, level, message, total):
lev=int(level)
assert lev >= self.min_level and lev <= self.max_level,\
"input level not within current limits"
#skip a space before level 1 statements
if lev in self.newline_before:
self.writeLine('')
#s1 and s2 are number of spaces for formatting
s1 = lev * self.level_indent
s2 = self.total_width - s1
#initialize fstr to the correct number of spaces
fstr='{{0:{0:d}s}} {{1:{1:d}s}}'.format(s1,s2)
# Number format string is right justified within number_width
number_format='{{2:-{0:d}d}}'.format(self.number_width)
fstr+=number_format
self.debugPrint('level {0:d} format str= {1:s}'.format(lev,fstr))
self.writeLine(fstr.format(' ', message, int(total)))
if __name__ == '__main__':
print "Testing ReportWithLevels.printLevel()"
pl=ReportWithLevels()
pl.open_outfile("testout.txt")
pl.writeLine("This is my report")
pl.number_width=12
tot=7
for level in [1,2,3,2,2,3,4,3,1]: #range(1,4):
msg='level {0:d} msg'.format(level)
tot=tot * 12
pl.printLevel(level,msg,tot)
#pl.printLevel(8,"level 8 msg",88) #test assert error
Mostly Linux & Python syntax notes and hyperlinks.
Sunday, July 27, 2014
python: Write totals at different indentation levels
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment