Java教程

java 如何调用python代码?

本文主要是介绍java 如何调用python代码?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Jython: Python for the Java Platform - Home | Jython

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.

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\nsys.path.append('pathToModules if they are not there by default')\nimport 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);

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

参考连接:

Calling Python in Java? - Stack Overflowhttps://stackoverflow.com/questions/8898765/calling-python-in-java

这篇关于java 如何调用python代码?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!