Producing Differently Formatted Output for the Same Dataset

If there are no options supplied for detailed reporting, the application only prints two numbers, which indicate the total number of exceptions found and the total number of different groups. You can use this information to quickly check the current status and also accumulate the records over a period of time and import that data into Excel or other tools to draw pretty graphs.

If you're planning to import report data to some other application it needs to comply with a format accepted by that application. If you're using Excel to create graphs, the most convenient file type for import would be CSV or Comma Separated Values, but if you just want to display this information on the screen you most likely want it to be more informative than just a pair of numbers separated by comma.

So I introduced an option that allows users to set a format they want to get the result in: either CSV or plain text. I then created two template strings that reference the same variables but provide different formatting:

TPL_SUMMARY['csv'] = "%(total)s, %(groups)s"

TPL_SUMMARy['text'] = "="*80 + "\nTotal exceptions: %(total)s\nDifferent groups: %(groups)s"

Then, depending on the format key supplied by the user, the print statement will select the appropriate formatting string and pass variables to it:

print TPL_SUMMARY[OPTIONS.format.lower()] % {'total': self.count, 'groups': len(categories)}

Note how you can pass variables to a formatted sting referencing them by name. This technique is really useful when you need to produce differently formatted output using the same set of variables.

Was this article helpful?

0 0

Post a comment