view 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
line wrap: on
line source
#!/usr/bin/env python
# Part of DML (Digital Music Laboratory)
# Copyright 2014-2015 Samer Abdallah, University College London
 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

# -*- coding: utf-8 -*-
__author__="samer"

import sys
import json

# Does computation described in spec, with following fields:
# "module" : string   ~ module names to import
# "function": string  ~ name of function to call
# "arguments" : list  ~ list of arguments to function
def import_and_apply(spec): 
    exec "from %s import %s" % (spec['module'], spec['function']) 
    return eval(spec['function'])(*spec['arguments'])

# call fn with input coverted from JSON on standard input and output
# written as JSON to standard output. 
# Success produces { "tag":"ok", "value":ReturnValue }.
# Error produces { "tag":"error", "value":Description }
def wrap(fn):
    # Function to convert unicode dict keys to ordinary strings.
    # Note that dict values are kept as unicode.
    def stringify(input):
        if isinstance(input, dict):
            return {key.encode('utf-8'):stringify(value) for key,value in input.iteritems()}
        elif isinstance(input, list):
            return [stringify(element) for element in input]
        else: return input

    try: reply = json.dumps({'tag':'ok', 'value':fn(stringify(json.load(sys.stdin)))})
    except Exception as e:
        reply = json.dumps({'tag':'error', 'value':str(e)})
    print(reply)
    
if __name__ == "__main__": wrap(import_and_apply)