[enh] Allow to encode printed result in json from the cli

This commit is contained in:
Jérôme Lebleu 2014-05-17 21:45:44 +02:00
parent c781d10b54
commit a205c04876
2 changed files with 14 additions and 5 deletions

View file

@ -81,7 +81,7 @@ def api(namespaces, port, routes={}, use_cache=True):
'use_cache': use_cache})
moulinette.run(port)
def cli(namespaces, args, use_cache=True):
def cli(namespaces, args, print_json=False, use_cache=True):
"""Command line interface
Execute an action with the moulinette from the CLI and print its
@ -90,6 +90,7 @@ def cli(namespaces, args, use_cache=True):
Keyword arguments:
- namespaces -- The list of namespaces to use
- args -- A list of argument strings
- print_json -- True to print result as a JSON encoded string
- use_cache -- False if it should parse the actions map file
instead of using the cached one
@ -100,7 +101,7 @@ def cli(namespaces, args, use_cache=True):
moulinette = init_interface('cli',
actionsmap={'namespaces': namespaces,
'use_cache': use_cache})
moulinette.run(args)
moulinette.run(args, print_json)
except MoulinetteError as e:
print('%s %s' % (colorize(m18n.g('error'), 'red'), e.strerror))
return e.errno

View file

@ -174,7 +174,7 @@ class Interface(BaseInterface):
self.actionsmap = actionsmap
def run(self, args):
def run(self, args, print_json=False):
"""Run the moulinette
Process the action corresponding to the given arguments 'args'
@ -182,6 +182,7 @@ class Interface(BaseInterface):
Keyword arguments:
- args -- A list of argument strings
- print_json -- True to print result as a JSON encoded string
"""
try:
@ -189,9 +190,16 @@ class Interface(BaseInterface):
except KeyboardInterrupt, EOFError:
raise MoulinetteError(errno.EINTR, m18n.g('operation_interrupted'))
if isinstance(ret, dict):
if ret is None:
return
# Format and print result
if print_json:
import json
print(json.dumps(ret))
elif isinstance(ret, dict):
pretty_print_dict(ret)
elif ret:
else:
print(ret)