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)

输出

扫描二维码关注公众号,回复: 16311255 查看本文章
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的四种方法

猜你喜欢

转载自blog.csdn.net/wzc3614/article/details/128666187
今日推荐