我想用 Java 调用我的 Python 类,但收到错误消息:
Manifest com.atlassian.tutorial:myConfluenceMacro:atlassian-plugin:1.0.0-SNAPSHOT : Classes found in the wrong directory
我通过 jar 在我的电脑上安装了 Jython。并将其添加到我的 pom 中(因为我使用的是 Maven 项目)。我究竟做错了什么?如何在 java 类中调用 python 方法?
我正在使用 python3。
POM
<!-- https://mvnrepository.com/artifact/org.python/jython-standalone -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.1</version>
</dependency>
JAVA类
package com.atlassian.tutorial.javapy;
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class InterpreterExample
{
PythonInterpreter interpreter = null;
public InterpreterExample()
{
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main( String gargs[] )
{
InterpreterExample ie = new InterpreterExample();
ie.execfile("hello.py");
PyInstance hello = ie.createClass("Hello", "None");
hello.invoke("run");
}
}
Python 类
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print ('Hello world!')
谢谢!
最佳答案
您的 Python 类中的缩进错误。正确的代码是:
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print ('Hello world!')
这样 __init__()
和 run()
是 Hello
类的方法,而不是全局函数。否则你的代码可以很好地工作。
请记住,Jython 的最新版本是 2.7.1 - 它与 Python3 不兼容。
关于java - Jython - 在 Java 中调用 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208475/