温馨提示×

java如何调用python

小亿
91
2024-11-30 05:59:18
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在Java中调用Python脚本,您可以使用以下方法之一:

方法1:使用Runtime类

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class JavaCallPython {
    public static void main(String[] args) {
        try {
            String pythonScriptPath = "/path/to/your/python/script.py";
            Process process = Runtime.getRuntime().exec("python " + pythonScriptPath);

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            process.waitFor();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法2:使用Jython库 首先,您需要下载Jython库并将其添加到Java项目的类路径中。下载地址:https://www.jython.org/downloads.html

然后,您可以使用以下代码调用Python脚本:

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

public class JavaCallPython {
    public static void main(String[] args) {
        try (PythonInterpreter interpreter = new PythonInterpreter()) {
            interpreter.execfile("/path/to/your/python/script.py");

            PyObject result = interpreter.eval("your_function_name()");
            String output = (String) result.__tojava__(String.class);

            System.out.println(output);
        }
    }
}

请注意,这些方法可能需要根据您的项目需求进行调整。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python怎么调用java类

0