PageRenderTime 157ms CodeModel.GetById 40ms app.highlight 64ms RepoModel.GetById 47ms app.codeStats 1ms

/src/googlecl/discovery/output.py

http://googlecl.googlecode.com/
Python | 59 lines | 24 code | 4 blank | 31 comment | 8 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
15
16"""Subfunctions for GoogleCL.
17
18Manages the formatting and output of generated responses
19"""
20import pprint
21
22def output(resp, mode = 'pprint'):
23  """Outputs the generated response according to defined formatting
24
25  Args:
26    resp: The actual response to be formatted and displayed
27    mode: What type of formatting is used
28  """
29  if mode == 'none':
30    print resp
31  elif mode == 'pprint':
32    pprint.pprint(resp)
33  elif mode == 'clean':
34    cprint(resp)
35
36def cprint(resp, st=1):
37  """ Displays a json object, dict, or list
38  More readable that pprint, but interchangeable.
39  Recursively calls itself to display nested subfields
40
41  Args:
42    resp: The object to be displayed
43    st: A counter for the current indentation
44  """
45  for arg in resp:
46    if isinstance(resp, dict):
47      if isinstance(resp[arg], dict) or isinstance(resp[arg], list):  
48        print (' '*st) + arg + ":"
49        cprint(resp[arg], st+2)
50      else:
51       try:
52        print (' '*st) + arg + ": " + str(resp[arg])
53       except UnicodeEncodeError:
54        print (' '*st) + arg + ": " + resp[arg]
55    else:
56      if isinstance(arg, dict) or isinstance(arg, list):
57        cprint(arg, st)
58      else:
59        print (' '*st) + arg