onlyforbopi
9/26/2018 - 12:49 PM

PRETTY PRINTING

  1. Pretty print (List or dictionary) for review
  2. Pyformat (List/Tuple or dictionary) for later use
def py_format(input, file_ot):
  '''
  Name: py_format
  Description: Outputs a file that contains the 
               definition of <input> ready to be
               imported (See Notes and sample code)
  Input: <input data structure> <filename>
  Output: <filename> that contains input in python format
  Usage: py_format(project_info, "OUTDATA.py")
  Notes: 
        py_format(project_info, "OUTDATA.py")
        import OUTDATA
        data = OUTDATA.allData
  Notes2: Check also in 'Python Useful Tricks'
  '''
    # check if file_ot ends in .py
    if file_ot.lower().endswith('.py'):
        try:
            resultFile = open(file_ot, 'w')
            resultFile.write('allData = ' + pprint.pformat(input))
            resultFile.close()
        except:
            print("Problem loading data to: " + str(file_ot))
            return False
        else:
            return True
def pretty_print(input, indent_depth):
  '''
  Name: pretty_print
  Description: pretty_prints a data structure
  Input: <List/Tuple/Dict>, indent_depth
  Output: stdout
  Usage: pretty_print(dict_in, 4)
  Notes: Works on any kind of data structure. 
  Requires: pprint module
  '''
    import pprint
    try:
        pprint.pprint(input)
        #pprint.PrettyPrinter(indent=indent_depth)
    except:
        print("Pretty print failed")