Java中使用Jython执行Python脚本时requests模块导入失败问题
解决Jython无法加载Python库(requests)的问题
核心问题分析
你当前的错误源于两处关键配置问题:
python.path设置错误:你指定的是Python可执行文件路径,而Jython需要的是Python第三方库所在的site-packages目录路径,才能找到requests等库。- 未启用PythonInterpreter初始化:你注释了
PythonInterpreter.initialize代码,导致配置完全未生效。
另外,你的Python脚本存在缩进错误,会引发语法异常,也需要一并修正。
具体修复步骤
1. 修正python.path配置
找到你的Anaconda环境下的site-packages目录,典型路径为:/Users/milind.yadav/anaconda3/lib/python3.9/site-packages(请根据你实际的Python版本替换3.9)
将Properties中的python.path设置为该目录路径,而非Python可执行文件路径。
2. 启用并正确初始化PythonInterpreter
取消注释PythonInterpreter.initialize代码,确保配置参数生效。
3. 修复Python脚本的缩进问题
脚本中import语句有多余缩进,需去除缩进,保持import顶格书写。
4. (可选)确保requests版本兼容
部分新版本requests依赖CPython专属特性,Jython无法运行。若修正路径后仍有问题,建议安装兼容版本:
pip install requests==2.27.1
修改后的Java代码
public void get_Inv_hash_ids(String token ,String url ,String url1) { try { // 替换为你的site-packages目录实际路径 String pythonLibPath = "/Users/milind.yadav/anaconda3/lib/python3.9/site-packages"; Properties properties = new Properties(); properties.setProperty("python.path", pythonLibPath); // 启用初始化,让配置生效 PythonInterpreter.initialize(System.getProperties(), properties, new String[0]); PythonInterpreter interpreter = new PythonInterpreter(); // 执行Python脚本 interpreter.execfile("/Users/milind.yadav/Downloads/batch_id_script.py"); // 获取Python函数引用 PyObject invoice_ids = interpreter.get("batch_id_fetcher"); // 调用函数并传递参数 PyObject result = invoice_ids.__call__(new PyString(token), new PyString(url), new PyString(url1)); String concatenated_invoice_ids = (String) result.__tojava__(String.class); System.out.println("Invoice Hashes: " + concatenated_invoice_ids); interpreter.close(); } catch (Exception e) { System.out.println("Exception occured ..."+e.getMessage()); e.printStackTrace(); } }
修改后的Python脚本
import requests import json from jsonpath_ng import jsonpath, parse def batch_id_fetcher(token,batchurl,url): invoice_object_ids=[] header = {"Authorization" : "Token "+token} batch_response=requests.get(batchurl, headers=header) batch_data=json.loads(batch_response.text) invoice_object_ids= batch_data["results"][0]["exported_invoice_ids"] inv_url = url+"invoices/?object_id=" header = {"Authorization" : "Token "+token} invoice_hash_list=[] invoice_hashes="" for i in invoice_object_ids: n_url=inv_url+str(i) response = requests.get(n_url, headers=header) json_data = json.loads(response.text) invoice_hash_list.append(json_data["results"][0]["id"]) invoice_hashes = ",".join(str(i) for i in invoice_hash_list) return invoice_hashes
内容的提问来源于stack exchange,提问作者Milind Yadav
相关产品推荐
相关产品推荐

