实际上,我是python中的新手。在这里,我想从python类中获取输出。但在这里,我从java输入String。
这是java代码:
String word;
Scanner in = new Scanner(System.in);
System.out.println("input: ");
word = in.nextLine();
TryinPythonToJavaAgain ie = new TryinPythonToJavaAgain();
ie.execfile("~\\hello.py");
PyInstance hello = ie.createClass("Hello", word);
hello.invoke("run");
python代码:
class Hello:
def __init__(self, abc):
self.abc = abc
def run(self):
print(self.abc)
如果我输入:“你好” 我有这样的错误:
输入: 你好 线程“main”Traceback中的异常(最近一次调用最后一次): 文件“”,第1行,in NameError:未定义名称“hello” Java结果:1
如果我输入> 2个字(例如“hello world”),我有这样的错误:
输入: 你好,世界 线程“main”中的异常SyntaxError :(“输入'世界'没有可行的选择”,('',1,12,'Hello(hello world)\ n')) Java结果:1
我应该在这段代码中修复什么?感谢
答案 0 :(得分:0)
如果createClass方法中的代码看起来像这样...
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
...然后我认为你需要在opts变量周围添加引号。上面的代码来自here,因为"无"变成this.interpreter.eval(className(None)),它是有效的,而你的变成this.interpreter.eval(className(hello world)),它不是。
我没有尝试过,但是this.interpreter.eval(className(" hello world"))似乎更有效。