java - 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!')
谢谢!
解决方案
您的 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。
推荐阅读
- git - Git 错误:与 git 已知的任何文件都不匹配
- c# - .Net Core 2.2 Cookie 认证问题
- python - 具有多个元素的数组的真值是不明确的。麻木的错误
- reactjs - 如何传递浏览器属性以响应应用程序与 MSBOT 的对话?
- javascript - ReactJS Material-UI:仅接受 TextField 中的正无符号整数值
- css - MiniCssExtractPlugin 没有链接到我的 html 文件
- azure-cognitive-search - 如何获取要在构面和过滤器中使用的键和值
- android - Flutter 中的 Google 标签管理器依赖项
- angular - 如何在角度 6 中的动态向导中从表单中检索数据
- c# - 创建类实例时解决依赖关系