以下代码想通过测试,必须有一个前提:电脑上安装了Python环境。不太习惯说废话,直接上代码了。
以下是用于测试的python代码(mytest.py):
# 因为用户到了参数处理,所以需要引用
import argparsedef test(uname, msg):return uname + ',你好,你发来的消息是:' + msgdef main():parser = argparse.ArgumentParser(description="调用测试")# 此处uname的命名,在调用时会用到parser.add_argument("--uname", type=str, help="传入的用户名")parser.add_argument("--msg", type=str, help="传入的消息")args = parser.parse_args()result = test(uname=args.uname, msg=args.msg)# 输出返回值,若有调用,对方可获取print(result)if __name__ == "__main__":main()
以下是Java代码:
public void test() {try{// 工作目录String currentDirectory = System.getProperty("user.dir");// 注意开头的testPython根据实际情况进行调整,因为我将Python代码和Java代码放入到了同一个项目中,所以这么写String pythonScriptRelativePath = "testPython/src/main/java/com/mytest.py";// py文件的具体路径String pythonScriptPath = currentDirectory + File.separator + pythonScriptRelativePath;// 执行 Python 脚本,带有参数ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath,"--uname", "Vincent Lu", "--msg", "收到消息了吗?");// 读取脚本的标准输出Process process = processBuilder.start();InputStream stdout = process.getInputStream();// 此处,我用了GBK,大家可根据实际情况进行调整BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, "GBK"));String line;while ((line = reader.readLine()) != null) {System.out.println("收到Python的返回值: " + line);}// 若发生错误,会执行以下内容InputStream stderr = process.getErrorStream();BufferedReader errorReader = new BufferedReader(new InputStreamReader(stderr));while ((line = errorReader.readLine()) != null) {System.out.println("错误内容: " + line);}// 等待进程结束并获取退出值int exitValue = process.waitFor();System.out.println("Exit value: " + exitValue);} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}
关于参数,有一点需要注意一下,若Python想接收一个dict类型的参数,在parser.add_argument("--dictData", type=str, help="传入的dict类型数据,理论上是一个JSON") 配置中,type依旧可以使用str类型,但是,在使用过程中,需要eval转换一下。如下:
result = test(dictData=eval(args.dictData))
更有趣的是,在JAVA中想传递JSON串,我必须得写成
String speedJson = "{\\\"SPEED\\\":[35, 95, 92, 92, None, 90, 93, 90, None, None, None, None, None, None, None, None, None]}"
我不太明白,为什么要加3个斜杠。
好啦,就到这里吧,我是来自北京天码科技的卢泽。