首页 > 解决方案 > 如何在 java 中运行这个 python 脚本?

问题描述

我想在我的 java 应用程序中使用这个脚本:https ://github.com/jcapona/amazon-wishlist-scraper 。

我环顾四周,并尝试像这样执行脚本:


public static void main(String[] args) throws IOException  {
        String s = null;
        Process p = Runtime.getRuntime().exec("python C:\\\\Users\\\\Home\\\\work\\\\test.py");
         BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));
         while ((s=stdInput.readLine()) != null) {
             System.out.println(s);
         }
    }

但我没有得到任何输出。我需要什么才能运行这个特定的脚本?

标签: javapython

解决方案


你可以这样使用:

String command = "python /c start python path\to\script\script.py>";
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new 
                              InputStreamReader(p.getInputStream()));
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    String line;
    while ((line = stdInput.readLine()) != null) {
        System.out.println(line);
      }
      stdInput.close();
      while ((line = stdErr.readLine()) != null) {
        System.out.println(line);
      }
      stdErr.close();
      p.waitFor();
      System.out.println("Done.");

p.destroy();

Protip:始终从文件资源管理器选项卡中复制您的路径

并且由于您收到 JSON 响应,请尝试使用 GSON 库对其进行解析。

如果您想使用 java 在 python 上大量工作,请尝试探索Jython


推荐阅读