Java中调用Python方法总结及踩坑记录

前言

最近在项目中需要通过Java调用Python脚本,在网上搜了很多博客,整个实操过程也踩了不少坑,因此通过这篇文章对Java中调用Python以及碰到的问题做一个总结。

调用方式

通过Runtime进行调用

例子如下:

public class InvokeByRuntime {
	/**
	 * @param args
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws IOExceptionInterruptedException {
		String exe = "python";
		String command = "D:\\calculator_simple.py";
		String num1 = "1";
		String num2 = "2";
		String[] cmdArr = new String[] {exe, command, num1, num2};
		Process process = Runtime.getRuntime().exec(cmdArr);
		InputStream is = process.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		String str = dis.readLine();
		process.waitFor();
		System.out.println(str);
	}
}

caculator_simple.py:

# coding=utf-8
from sys import argv

num1 = argv[1]
num2 = argv[2]
sum = int(num1) + int(num2)
print sum

输出:

3

这种方式与直接执行Python程序的效果是一样的,Python可以读取Java传递的参数,但缺点是不能在Python中通过return语句返回结果,只能将返回值写到标准输出流中,再用Java读取Python的输出值

通过Jython调用

在maven项目中引入依赖,这里用的是最新版

<dependency>
  <groupId>org.python</groupId>
  <artifactId>jython-standalone</artifactId>
  <version>2.7.2</version>
</dependency>
无参数无返回值

例子:

package com.poas.utils;
import org.python.util.PythonInterpreter;

public class PythonTest {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        //这里用的是相对路径,注意区分
        interpreter.execfile("core/src/main/java/com/poas/utils/plus.py");
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

plus.py:

a = 1
b = 2
print(a + b)

输出

3
有参数有返回值

例子:

package com.poas.utils;

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class PythonTest {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        //我在这里使用相对路径,注意区分
        interpreter.execfile("core/src/main/java/com/poas/utils/plus.py");

        // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a = 5, b = 10;
        //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("the anwser is: " + pyobj);
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

plus.py:

def add(a,b):
    return a+b

执行后得到结果15

踩坑记录

网上大部分博客就到以上部分了,但我在实操中还遇到了以下问题

报错: Non-ASCII character in file xxx, but no encoding declared

原因是python文件中有中文,识别不了,就算是注释也不行

在python文件第一行中添加以下内容,问题解决

# -*- coding: utf-8 -*-

报错:Cannot create PyString with non-byte value

最开始用的jython版本是2.7.0,在Java中传递字符串时报了这个错:Cannot create PyString with non-byte value;在网上查了说是版本问题,于是将版本更新为2.7.2,问题解决

报错:ImportError: No module named xxx

我在python文件中引用了第三方库,结果出现该错误

Java文件:

public class PythonTest {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();       
        interpreter.execfile("core/src/main/java/com/poas/utils/hello.py");        
        PyFunction pyFunction = interpreter.get("hello", PyFunction.class);        
        PyString str = Py.newString("hello world!");
        PyObject pyobj = pyFunction.__call__(str);
        System.out.println(pyobj);
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

python文件:

import requests #此处这个包没有实际作用,只是为了复现报错
def hello(str) :
    print(str)
    return str

报错:

ImportError: No module named requests

首先检查是否安装了对应的第三方库,在python环境下成功后,说明已安装对应模块;在网上搜索后发现要配置python的系统路径,代码如下:

public class PythonTest {
    public static void main(String[] args) {
		// 配置python的系统路径
        System.setProperty("python.home", "/usr/bin/python2.7");

        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("core/src/main/java/com/poas/utils/hello.py");        
        PyFunction pyFunction = interpreter.get("hello", PyFunction.class);        
        PyString str = Py.newString("hello world!");
        PyObject pyobj = pyFunction.__call__(str);
        System.out.println(pyobj);
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

配置完成后,依然报错

继续查资料,除了上述配置外,还要将被引用的第三方库的路径添加到系统环境变量中,代码如下:

public class PythonTest {
    public static void main(String[] args) {
        // 配置python的系统路径
        System.setProperty("python.home", "/usr/bin/python2.7");

        PythonInterpreter interpreter = new PythonInterpreter();
        // 添加第三方库的路径
        PySystemState sys = interpreter.getSystemState();
        sys.path.add("/Users/xxx/Library/Python/2.7/lib/python/site-packages");

        interpreter.execfile("core/src/main/java/com/poas/utils/hello.py");
        PyFunction pyFunction = interpreter.get("hello", PyFunction.class);
        PyString str = Py.newString("hello world!");
        PyObject pyobj = pyFunction.__call__(str);
        System.out.println(pyobj);
        interpreter.cleanup();
        interpreter.close();
    }
}

问题解决

参考文献:

在Java中调用Python
【Java】使用Java调用Python的四种方法

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的`ProcessBuilder`类来调用Python脚本,并指定要调用方法。下面是一个示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PythonMethodCaller { public static void main(String[] args) { try { // 构建Python脚本的调用命令(假设脚本名为example.py) ProcessBuilder pb = new ProcessBuilder("python", "example.py", "method_name"); // 启动进程并等待执行完成 Process process = pb.start(); int exitCode = process.waitFor(); // 检查进程退出代码 if (exitCode == 0) { // 读取Python脚本的输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } else { // 执行出错 System.err.println("Python脚本执行出错"); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 在上述示例,我们使用`ProcessBuilder`构建了一个调用Python脚本的命令,并指定了要调用方法名("method_name")。然后,我们启动进程并等待执行完成。如果进程的退出代码为0,表示执行成功,我们可以读取Python脚本的输出;否则,表示执行出错。 请注意,你需要将示例代码的`example.py`替换为你实际的Python脚本文件名,并将`method_name`替换为你要调用方法名。另外,确保你的系统上已经正确配置了Python环境。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值