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?
I think that your problem is that the python interpreter is interpreting the java variable keyname as a Python variable within the python program rather than as a string. Add quotes to around keyname and you won't get this error. I other words
Instead of using:
List<String> keys = (List<String>) interpreter
.eval("auth.get_keys_by_name(" + keyname+ ")");
Use this:
List<String> keys = (List<String>) interpreter
.eval("auth.get_keys_by_name('" + keyname+ "')");
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, ie 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, ie eval("auth.get_keys_by_name(\\"" + keyname + "\\")")
would evaluate auth.get_keys_by_name("abc")
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.