使用场景在很多情况,我们需要使用java去调用python的服务和功能
java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PythonScriptCaller {
public static void main(String[] args) {
try {
// 构建命令
ProcessBuilder pb = new ProcessBuilder("python3", "addwatermak_app.py", "Xiaoxin Air 14", "https://xxx.png", "1-1", "1711531502628-1d9359ec-45b9-49c3-9e2b-5518fa83ad7f-1mall1.png", "0");
// 启动进程
Process process = pb.start();
// 读取标准输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 读取标准错误
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errorReader.readLine()) != null) {
System.err.println(line);
}
// 等待进程完成
int exitCode = process.waitFor();
// 检查进程退出代码
if (exitCode == 0) {
System.out.println("Python script executed successfully.");
} else {
System.err.println("Error: Python script execution failed with exit code " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
python 代码
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Parse JSON data from command line")
parser.add_argument("deviceName", type=str, help="JSON data as a string")
parser.add_argument("img", type=str, help="JSON data as a string")
parser.add_argument("imgKey", type=str, help="JSON data as a string")
parser.add_argument("imgName", type=str, help="JSON data as a string")
parser.add_argument("languageCode", type=str, help="JSON data as a string")
args = parser.parse_args()
device_name = args.deviceName
img_url = args.img
img_key = args.imgKey
img_name = args.imgName
logger.info(f"接收到deviceName: {device_name}, img_url: {img_url}, img_key: {img_key}, img_name: {img_name}")
python 运行命令:
python addwatermak_app.py "test" "https://xxx.png" "1-1" "1711531502628-1d9359ec-45b9-49c3-9e2b-5518fa83ad7f-1mall1.png" "0"
注意事项:
在书写python程序的时候要,全部的图片目录,外部资源文件地址要写成“绝对路径”,以免发生错误,导致python程序运行不起来。