如何在Java/Groovy脚本任务中调用外部Python函数?
可行解决方案
方案1:搭建Python API服务(推荐复杂逻辑/高复用场景)
用FastAPI快速构建轻量API,步骤如下:
- 安装依赖:
pip install fastapi uvicorn
- 编写API代码(保存为
word_count_api.py):
from fastapi import FastAPI app = FastAPI() def getWordCount(string): return len(string.split()) @app.post("/count-words") async def count_words(request: dict): input_str = request.get("string", "") return {"count": getWordCount(input_str)}
- 启动API服务:
uvicorn word_count_api:app --host 0.0.0.0 --port 8000
- Java调用示例:
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class PythonApiCaller { public static void main(String[] args) throws Exception { String testing = "This is a string."; JsonObject requestBody = new JsonObject(); requestBody.addProperty("string", testing); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8000/count-words")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString())) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); JsonObject responseJson = JsonParser.parseString(response.body()).getAsJsonObject(); int count = responseJson.get("count").getAsInt(); System.out.println("Word count: " + count); } }
- Groovy简化调用示例:
import groovy.json.JsonBuilder import groovy.json.JsonSlurper def testing = "This is a string." def requestBody = new JsonBuilder([string: testing]).toString() def response = new URL("http://localhost:8000/count-words").openConnection() response.setRequestMethod("POST") response.setRequestProperty("Content-Type", "application/json") response.doOutput = true response.outputStream.write(requestBody.getBytes()) def result = new JsonSlurper().parseText(response.inputStream.text) int count = result.count println "Word count: ${count}"
方案2:Java/Groovy直接调用Python进程(适合简单场景/无需长期服务)
如果工作流环境允许执行外部进程,可跳过API直接调用脚本:
- 编写可独立运行的Python脚本(保存为
word_counter.py):
import sys def getWordCount(string): return len(string.split()) if __name__ == "__main__": if len(sys.argv) > 1: input_str = sys.argv[1] print(getWordCount(input_str))
- Java调用示例:
import java.io.BufferedReader; import java.io.InputStreamReader; public class PythonProcessCaller { public static void main(String[] args) throws Exception { String testing = "This is a string."; ProcessBuilder pb = new ProcessBuilder("python", "/path/to/word_counter.py", testing); Process process = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String output = reader.readLine(); int count = Integer.parseInt(output); System.out.println("Word count: " + count); process.waitFor(); } }
- Groovy简化调用示例:
def testing = "This is a string." def process = ["python", "/path/to/word_counter.py", testing].execute() process.waitFor() int count = process.in.text.trim().toInteger() println "Word count: ${count}"
注意事项
- 若涉及神经网络等重逻辑,API服务建议搭配Gunicorn做进程管理,避免单请求阻塞服务
- 生产环境需给API添加认证(如API Key),防止未授权访问
- 调用时需处理异常场景:API超时、脚本执行失败、输入参数格式错误等
内容的提问来源于stack exchange,提问作者Wilko
相关产品推荐
相关产品推荐

