如何从java类调用python方法? [英] How to call a python method from a java class?
问题描述
我在Java项目中使用Jython。
I am using Jython within a Java project.
我有一个Java类: myJavaClass.java
和一个Python类: myPythonClass.py
I have one Java class: myJavaClass.java
and one Python class: myPythonClass.py
public class myJavaClass{
public String myMethod() {
PythonInterpreter interpreter = new PythonInterpreter();
//Code to write
}
}
Python文件如下:
The Python file is as follows:
class myPythonClass:
def abc(self):
print "calling abc"
tmpb = {}
tmpb = {'status' : 'SUCCESS'}
return tmpb
现在的问题是我想从 myMethod中调用我的Python文件的
我的Java文件的方法并打印结果。 abc()
方法
Now the problem is I want to call the abc()
method of my Python file from the myMethod
method of my Java file and print the result.
推荐答案
If I read the docs right, you can just use the eval
function:
interpreter.execfile("/path/to/python_file.py");
PyDictionary result = interpreter.eval("myPythonClass().abc()");
或者如果你想得到一个字符串:
Or if you want to get a string:
PyObject str = interpreter.eval("repr(myPythonClass().abc())");
System.out.println(str.toString());
如果你想从Java变量中提供一些输入,你可以使用事先设置
,然后在Python代码中使用该变量名:
If you want to supply it with some input from Java variables, you can use set
beforehand and than use that variable name within your Python code:
interpreter.set("myvariable", Integer(21));
PyObject answer = interpreter.eval("'the answer is: %s' % (2*myvariable)");
System.out.println(answer.toString());
这篇关于如何从java类调用python方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!