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的四种方法

<think>嗯,用户想了解如何实现快递查询接口,还有相关的API文档和第三方物流查询接口的信息。我需要先整理一下已有的引用资料,看看有哪些关键点需要覆盖。 首先,用户提供的引用里提到了快递鸟的API接口,支持多种开发语言,比如Java、C#、PHP、Python等。还有顺丰的API接口调用示例,包括自动识别快递公司和需要参数如单号和手机号后四位。另外,快递地址解析接口的应用场景,以及配置Maven依赖的注意事项。这些都是需要整合到回答中的关键信息。 接下来,我得考虑用户可能的实际需求。用户可能是一个开发者,想要在自己的应用中集成快递查询功能,所以需要具体的步骤和代码示例。同时,用户可能关心不同API提供商的特点,比如快递鸟支持多家快递公司,而顺丰可能需要特定的参数。此外,注意事项比如API密钥、请求频率限制、错误处理也是重要的点。 需要分步骤讲解实现流程,从注册账号、获取API密钥,到编写请求参数,发送HTTP请求,处理响应结果。每个步骤要简明扼要,同时提供示例代码,比如Python的requests库的使用。另外,第三方接口的选择比较,比如快递鸟、阿里云、顺丰各自的优缺点,帮助用户根据需求选择。 可能还需要提到快递地址解析接口的应用,如引用3中提到的,可以和物流查询接口搭配使用,提升整体效率。此外,注意事项部分要强调参数校验、数据缓存、错误日志等实际开发中常见的问题,避免用户。 用户的问题还包括快递查询API文档和第三方接口,所以在回答中需要给出各个提供商的文档链接,方便用户查阅。同时,生成的相关问题要覆盖性能优化、数据准确性、安全性等,帮助用户进一步探索。 最后,要确保回答符合系统级指令,数学公式正确使用,行内用$,独立公式用$$,但在这个问题中可能用不上太多数学表达式,但要注意LaTeX的正确使用。引用标识要正确添加,比如每个引用末尾的[^1]、[^2]等,确保来源清晰。 总结一下,回答结构大致分为实现步骤、第三方接口对比、注意事项,以及相关问题。确保内容清晰、步骤详细,代码示例正确,并且引用相关文档链接,帮助用户顺利实现快递查询接口的集成。</think>### 快递查询接口实现方法 #### 1. 实现流程与核心步骤 快递查询接口主要通过调用第三方物流平台提供的API实现,以下是具体实现步骤: **1.1 注册并获取API密钥** - 以快递鸟为例,注册账号后需申请企业级API Key。 - 示例:快递鸟API支持多语言调用Java/Python/C#等),需在请求头中携带`EBusinessID`和`ApiKey`。 **1.2 构造请求参数** - **必填参数**:快递单号(如`SF1525026605001`)、快递公司编码(支持自动识别)、手机号后四位(顺丰等需验证)[^4]。 - 请求数据需按文档要求进行JSON/XML格式化,并计算签名(如MD5或SHA1加密)[^5]。 **1.3 发送HTTP请求** ```python import requests import hashlib import json # 示例:快递鸟API请求(Python) def query_express(express_no, company_code): api_url = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx" app_id = "your_EBusinessID" app_key = "your_ApiKey" # 构造请求数据 request_data = { "ShipperCode": company_code, "LogisticCode": express_no } data_sign = hashlib.md5(json.dumps(request_data).encode() + app_key.encode()).hexdigest() headers = {"Content-Type": "application/x-www-form-urlencoded"} params = { "RequestData": json.dumps(request_data), "EBusinessID": app_id, "RequestType": "1002", "DataSign": data_sign, "DataType": "2" } response = requests.post(api_url, headers=headers, data=params) return response.json() ``` **1.4 解析响应结果** - 成功响应包含物流轨迹列表,例如: ```json { "Success": true, "Traces": [ {"AcceptTime": "2023-01-01 10:00", "AcceptStation": "已收件"}, {"AcceptTime": "2023-01-02 15:30", "AcceptStation": "到达转运中心"} ] } ``` #### 2. 第三方物流查询接口对比 | 服务商 | 支持快递公司数 | 特色功能 | 开发文档链接 | |-----------|----------------|---------------------------|----------------------------------| | 快递鸟 | 1600+ | 多语言支持、自动识别单号 | [快递鸟API文档] | | 阿里云 | 主流快递 | 顺丰专属接口、高并发处理 | [阿里云快递API][^4] | | 顺丰开放平台| 仅顺丰 | 精准轨迹、签收验证 | [顺丰API文档] | #### 3. 注意事项 1. **参数校验**:需验证单号有效性(如顺丰单号为12位纯数字)。 2. **频率限制**:企业级API通常限制每秒10-50次请求。 3. **数据缓存**:建议对查询结果缓存30分钟以降低API调用量。 4. **错误处理**:需处理`网络超时`、`签名错误`等异常,并记录日志[^5]。 #### 4. 相关API文档 - 快递鸟企业级接口文档:[下载链接][^2] - 顺丰API接入指南:[官方文档] - 地址智能解析接口(搭配使用):[说明文档][^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值