java调用python脚本,用到tensorflow、keras等第三方库

https://blog.csdn.net/jstlovely/article/details/121247764?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168110434116800227452800%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168110434116800227452800&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-9-121247764-null-null.142^v82^insert_down38,201^v4^add_ask,239^v2^insert_chatgpt&utm_term=java%E8%B0%83%E7%94%A8Python%20keras&spm=1018.2226.3001.4187

 

 

public static void main(String[] args) {
  // 获取当前工作目录(添加)
  String basePath = System.getProperty("user.dir");
  // 传入数据(添加)
  String inputStr = a+ "," + b;
// 创建固定大小为2的线程池 ExecutorService executor = Executors.newFixedThreadPool(2); // 提交任务执行 Callable<Integer> task = new Callable<Integer>(){ @Override public Integer call() throw Exception { //一定要用虚拟环境下的python路径 String[] args1=new String[]{"D:\\SoftWare\\Anaconda\\envs\\jst\\python.exe","F:\\Python_Project\\test.py",inputStr}; Process pr = Runtime.getRuntime().exec(args1); String line; BufferedReader stderr = new BufferedReader(new InputStreamReader(pr.getErrorStream(),"GBK")); while ((line = stderr.readLine()) != null) { System.out.println("stderr:" + line); } stderr.close(); BufferedReader stdout = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK")); while ((line = stdout.readLine()) != null) { System.out.println("stdout:" + line); } stdout.close(); return pr.waitFor(); } }; Future<Integer> future = executor.submit(task); try{ int exitVal = pr.waitFor(); if (0 != exitVal) { System.out.println("执行脚本失败"); } System.out.println("执行脚本成功"); } catch (Exception e){ System.out.println("执行脚本出现异常:" + e.getMessage()); } finally { // 关闭线程池 executor.shutdown(); }


// python调用输入
input_data = np.array([float(x) for x in sys.argv[1].split(',')])

 

posted on 2023-04-21 08:50  吴XX  阅读(27)  评论(0编辑  收藏  举报