[英]Jython - Calling Python Class in Java
I want to call my Python class in Java, but I get the error message: 我想用Java调用我的Python类,但收到错误消息:
Manifest com.atlassian.tutorial:myConfluenceMacro:atlassian-plugin:1.0.0-SNAPSHOT : Classes found in the wrong directory 清单com.atlassian.tutorial:myConfluenceMacro:atlassian-plugin:1.0.0-SNAPSHOT:在错误目录中找到的类
I installed Jython on my pc via jar. 我通过jar在计算机上安装了Jython。 And added it in my pom (because I am using a Maven Project). 并将其添加到我的pom中(因为我正在使用Maven项目)。 What am I doing wrong? 我究竟做错了什么? How can I call a python method inside my java class? 如何在我的Java类中调用python方法?
I am using python3 . 我正在使用python3 。
<!-- https://mvnrepository.com/artifact/org.python/jython-standalone -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.1</version>
</dependency>
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");
}
}
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print ('Hello world!')
Thank you! 谢谢!
You have wrong indentation in your Python class. 您的Python类中的缩进错误。 Correct code is: 正确的代码是:
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print ('Hello world!')
so that __init__()
and run()
are methods of your Hello
class, not global functions. 因此__init__()
和run()
是Hello
类的方法,而不是全局函数。 Otherwise your code works nicely. 否则,您的代码将运行良好。
And please remember that the latest version of Jython is 2.7.1 - it is not Python3 compatible. 并且请记住,Jython的最新版本是2.7.1-它与Python3不兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.