PageRenderTime 38ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/googlecl/discovery/output.py

http://googlecl.googlecode.com/
Python | 59 lines | 24 code | 4 blank | 31 comment | 14 complexity | 9b8e6bf6d88a93e6cf542a3eb3835fc1 MD5 | raw file
  1. # Copyright (C) 2010 Google Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Subfunctions for GoogleCL.
  15. Manages the formatting and output of generated responses
  16. """
  17. import pprint
  18. def output(resp, mode = 'pprint'):
  19. """Outputs the generated response according to defined formatting
  20. Args:
  21. resp: The actual response to be formatted and displayed
  22. mode: What type of formatting is used
  23. """
  24. if mode == 'none':
  25. print resp
  26. elif mode == 'pprint':
  27. pprint.pprint(resp)
  28. elif mode == 'clean':
  29. cprint(resp)
  30. def cprint(resp, st=1):
  31. """ Displays a json object, dict, or list
  32. More readable that pprint, but interchangeable.
  33. Recursively calls itself to display nested subfields
  34. Args:
  35. resp: The object to be displayed
  36. st: A counter for the current indentation
  37. """
  38. for arg in resp:
  39. if isinstance(resp, dict):
  40. if isinstance(resp[arg], dict) or isinstance(resp[arg], list):
  41. print (' '*st) + arg + ":"
  42. cprint(resp[arg], st+2)
  43. else:
  44. try:
  45. print (' '*st) + arg + ": " + str(resp[arg])
  46. except UnicodeEncodeError:
  47. print (' '*st) + arg + ": " + resp[arg]
  48. else:
  49. if isinstance(arg, dict) or isinstance(arg, list):
  50. cprint(arg, st)
  51. else:
  52. print (' '*st) + arg