首页 > 解决方案 > Jython - 在 Java 中调用 Python 类

问题描述

我想用 Java 调用我的 Python 类,但收到错误消息:

Manifest com.atlassian.tutorial:myConfluenceMacro:atlassian-plugin:1.0.0-SNAPSHOT :在错误目录中找到的类

我通过 jar 在我的电脑上安装了 Jython。并将其添加到我的 pom 中(因为我使用的是 Maven 项目)。我究竟做错了什么?如何在我的 java 类中调用 python 方法?
我正在使用 python3

聚甲醛

<!-- 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!')

谢谢!

标签: javapythonmavenjython

解决方案


您的 Python 类中有错误的缩进。正确的代码是:

class Hello:  
    __gui = None  


    def __init__(self, gui):  
        self.__gui = gui  


    def run(self):  
        print ('Hello world!')

所以__init__()andrun()是你的Hello类的方法,而不是全局函数。否则,您的代码运行良好。

请记住,最新版本的 Jython 是 2.7.1 - 它不兼容 Python3。


推荐阅读