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