SpringBoot调用Python脚本
一、前言
SpringBoot作为后端开发框架,有强大且方便的处理能力。但是作为一个结合数据分析+前台展示的网站来说,后端的数据处理模块使用python脚本要更加方便。
本文主要介绍如何利用Springboot框架调用python脚本
二、方法
其实一句话来说就是利用springboot(Java)中的命令行进行调用,直接上代码。
1、代码
-
python文件可以放在任意位置,但是如果后续需要进行部署的话建议放在springboot自带的静态文件夹目录下
-
在springboot中插入方法
public boolean testPython(String filePath){ String command = "cmd.exe /c cd" + path //此处插入python文件的路径 + "&& start python xxx.py " + "-f C:\Users\l00018749\Desktop\demo\";//这里利用了python的命令行机制可以传入参数 try { Process p = Runtime.getRuntime().exec(command); return true; } catch (IOException e) { e.printStackTrace(); return false; } }
-
python文件中的代码
// An highlighted block
if name == ‘main’:
parser=optparse.OptionParser()
parser.add_option(“-f”, “–file”, dest=“file”,
help=“write report to FILE”, metavar=“FILE”)
options, args=parser.parse_args()
file= options.file
hello_file = file+ ‘/hello.txt’
with open(hello_file, ‘w’) as file:
file.write(“yeeeeeeeeeeeeee”)
为了方便测试,可以把springboot中的方法暂时放到Application中
2、运行
- 为了方便展示我把方法中的代码复制到了application中,运行后可以看到在demo文件夹下已经生成了一个txt文件