From a205c04876fff336e9cddb5f7cd373be863bfee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Lebleu?= Date: Sat, 17 May 2014 21:45:44 +0200 Subject: [PATCH] [enh] Allow to encode printed result in json from the cli --- moulinette/__init__.py | 5 +++-- moulinette/interfaces/cli.py | 14 +++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/moulinette/__init__.py b/moulinette/__init__.py index 066a1f0b..f236f083 100755 --- a/moulinette/__init__.py +++ b/moulinette/__init__.py @@ -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 diff --git a/moulinette/interfaces/cli.py b/moulinette/interfaces/cli.py index 6ade958e..c169cda3 100644 --- a/moulinette/interfaces/cli.py +++ b/moulinette/interfaces/cli.py @@ -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)