如何从java类调用python方法?
我在 Java 项目中使用 Jython。
我有一个 Java 类:myJavaClass.java
和一个 Python 类:myPythonClass.py
public class myJavaClass{
public String myMethod() {
PythonInterpreter interpreter = new PythonInterpreter();
//Code to write
}
}
Python 文件如下:
class myPythonClass:
def abc(self):
print "calling abc"
tmpb = {}
tmpb = {'status' : 'SUCCESS'}
return tmpb
现在的问题是我想调用 我的 Python 文件的 abc()
方法来自 Java 文件的 myMethod
方法,并打印结果。
I am using Jython within a Java project.
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
}
}
The Python file is as follows:
class myPythonClass:
def abc(self):
print "calling abc"
tmpb = {}
tmpb = {'status' : 'SUCCESS'}
return tmpb
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我正确阅读了 文档,您只需使用 < a href="http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#eval(org.python.core.PyObject)" rel="noreferrer">
eval
函数:或者如果您想获取一个字符串:
如果您想为其提供一些来自 Java 变量的输入,您可以使用
set< /code> 事先,然后在 Python 代码中使用该变量名称:
If I read the docs right, you can just use the
eval
function:Or if you want to get a string:
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:如果我们需要运行一个带有参数的Python函数,并返回结果,我们只需要打印:
somme is the function in python module somme_x_y.py
If we need to run a python function that has parameters, and return results, we just need to print this:
somme is the function in python module somme_x_y.py
没有任何方法可以完全做到这一点(据我所知)。
不过,您有几个选择:
1)从 java 中执行 python,如下所示:
2)您可以使用 Jython 是“用 Java 编写的 Python 编程语言的实现”,从那里你可能会更幸运地做你想做的事情。
3)您可以使两个应用程序通过套接字或共享文件以某种方式进行通信
There isn't any way to do exactly that (that I'm aware of).
You do however have a few options:
1) Execute the python from within java like this:
2) You can maybe use Jython which is "an implementation of the Python programming language written in Java", from there you might have more luck doing what you want.
3) You can make the two applications communicate somehow, with a socket or shared file
您可以此处下载 Jython 2.7.0 - 独立 Jar。
然后...
然后...
You can download here Jython 2.7.0 - Standalone Jar.
Then ...
Then...