comparison dml-cla/python/json_wrapper.py @ 0:718306e29690 tip

commiting public release
author Daniel Wolff
date Tue, 09 Feb 2016 21:05:06 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:718306e29690
1 #!/usr/bin/env python
2 # Part of DML (Digital Music Laboratory)
3 # Copyright 2014-2015 Samer Abdallah, University College London
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 # -*- coding: utf-8 -*-
20 __author__="samer"
21
22 import sys
23 import json
24
25 # Does computation described in spec, with following fields:
26 # "module" : string ~ module names to import
27 # "function": string ~ name of function to call
28 # "arguments" : list ~ list of arguments to function
29 def import_and_apply(spec):
30 exec "from %s import %s" % (spec['module'], spec['function'])
31 return eval(spec['function'])(*spec['arguments'])
32
33 # call fn with input coverted from JSON on standard input and output
34 # written as JSON to standard output.
35 # Success produces { "tag":"ok", "value":ReturnValue }.
36 # Error produces { "tag":"error", "value":Description }
37 def wrap(fn):
38 # Function to convert unicode dict keys to ordinary strings.
39 # Note that dict values are kept as unicode.
40 def stringify(input):
41 if isinstance(input, dict):
42 return {key.encode('utf-8'):stringify(value) for key,value in input.iteritems()}
43 elif isinstance(input, list):
44 return [stringify(element) for element in input]
45 else: return input
46
47 try: reply = json.dumps({'tag':'ok', 'value':fn(stringify(json.load(sys.stdin)))})
48 except Exception as e:
49 reply = json.dumps({'tag':'error', 'value':str(e)})
50 print(reply)
51
52 if __name__ == "__main__": wrap(import_and_apply)