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