springboot如何优雅的调用python
- 使用Python的subprocess库,在Spring Boot的Controller中调用Python脚本。
示例代码:
@RequestMapping("/test")
public String test() throws IOException {
String[] cmd = new String[]{"python", "/path/to/python/script.py"};
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
String line = null;
while ((line = stdInput.readLine()) != null) {
output += line + "\n";
}
return output;
}
- 使用Python的Flask框架搭建一个简单的API,然后在Spring Boot中调用API。
在Python中,可以使用以下代码搭建一个简单的API:
from flask import Flask, request
app = Flask(__name__)
@app.route('/api')
def api():
# 处理请求参数
arg1 = request.args.get('arg1')
arg2 = request.args.get('arg2')
# 调用Python函数处理数据
result = python_function(arg1, arg2)
# 返回结果
return result
if __name__ == '__main__':
app.run(debug=True)
在Spring Boot中,可以使用以下代码调用API:
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:5000/api?arg1=value1&arg2=value2";
String result = restTemplate.getForObject(url, String.class);
其中,value1和value2是传递给Python函数的参数
原文地址: https://www.cveoy.top/t/topic/dpSL 著作权归作者所有。请勿转载和采集!