Search code examples
javapythonjython

Java calling Python function using PythonInterpreter


I have a python module auth.py:

keys= {
    "s1": ["k1", "k2"],
    "s2": ["k1", "k2"]
}

def get_keys_by_name(name):
    return keys[name]

And the calling Java code:

String keyname= "somename"
interpreter.exec("from services.framework import auth");
List<String> keys = (List<String>) interpreter
                .eval("auth.get_keys_by_name(" + keyname+ ")");

Each time i call the code i get a NameError form the argument (keyname) that i try to pass to the python code.

Anyone knows what i am doing wrong?


Solution

  • As per request my comment as an answer :)

    Passing a key with value abc to eval("auth.get_keys_by_name(" + keyname+ ")") would result in auth.get_keys_by_name(abc) being evaluated, i.e. the interpreter will probably look for a variable named abc and since that doesn't exist your get a NameError.

    Adding quotes (I'm no python expert so I don't know whether single or double quotes would be better) should fix that, i.e. eval("auth.get_keys_by_name(\"" + keyname + "\")") would evaluate auth.get_keys_by_name("abc").