java调用python脚本

有时候需要在java代码中调用python脚本来完成某些功能,如何调用呢?

最简单的方式就是使用java代码,运行python命令,执行python脚本,具体如下:

Java代码 

public static void main(String[] args) {
		Process proc;
		try {
			proc = Runtime.getRuntime().exec("python f:\\FaceAPI.py");
			BufferedReader in = proc.inputReader();
			BufferedReader errorReader = proc.errorReader();
			String line = null;
			while ((line = in.readLine()) != null) {
				System.out.println(line);
			}
			while ((line = errorReader.readLine()) != null) {
				System.out.println(line);
			}
			in.close();
			errorReader.close();
			proc.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

FaceAPI.py

import requests
import base64

'''
人像动漫化
'''

request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
# 二进制方式打开图片文件
img_url = 'f:\\1.jpeg'
f = open(img_url,'rb')
img = base64.b64encode(f.read())

params = {"image":img}
access_token = '24.12480192df9bf2cef461fc6040b4eaef.2592000.1656638033.282335-26356057'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    # print (response.json())
    data = base64.b64decode(response.json()['image'])
    #print(data)
    f1 = open(img_url,'wb')
    f1.write(data)
    f1.close()
    print('ren lian dong man hua chenggong!')

运行结果:

java调用python脚本_第1张图片

 注意:安装python时,

java调用python脚本_第2张图片

java调用python脚本_第3张图片 

你可能感兴趣的:(java,java,python)