java - Jython - 在 Java 中调用 Python 类

标签 java python maven jython

我想用 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/

相关文章:

Python继承初始化问题

java - 使用 Arrays.fill 时崩溃

java - 通过 Hashmap 对象处理值

c++ - NumPy 的 C++ : How to iterate over PyArrayObject without a segfault

java - 如何使用 Eclipse 为 Java 项目创建 pom.xml

java - 在docker中使用外部jar依赖

hibernate - 来自 Maven 的 Bean 中的 UnknownEntityTypeException

java - JDBC 上的 UnsupportedClassVersionError Java 教程

java - 转发后是否允许重定向请求?

python - Authlib token 未保存在数据库中