在 Java 中调用 Python? [英] Calling Python in Java?

查看:22
本文介绍了在 Java 中调用 Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用jython从java代码调用python函数,还是只能从python调用java代码?

I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python?

推荐答案

Jython: Python for the Java Platform - http://www.jython.org/index.html

Jython: Python for the Java Platform - http://www.jython.org/index.html

您可以使用 Jython 从 Java 代码轻松调用 Python 函数.只要您的 python 代码本身在 jython 下运行,即不使用一些不受支持的 c 扩展.

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

如果这对您有用,那肯定是您可以获得的最简单的解决方案.否则,您可以使用来自新 Java6 解释器支持的 org.python.util.PythonInterpreter.

If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

一个简单的例子 - 但我希望应该可以工作:(为简洁起见,没有进行错误检查)

A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys
sys.path.append('pathToModules if they are not there by default')
import yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

截至 2021 年,Jython 不支持 Python 3.x

As of 2021, Jython does not support Python 3.x

这篇关于在 Java 中调用 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆