简体   繁体   English

如何在 java 中运行此 python 脚本?

[英]How do I run this python script in java?

I want to use this script in my java app: https://github.com/jcapona/amazon-wishlist-scraper .我想在我的 java 应用程序中使用这个脚本: https://github.com/jcapona/amazon-wishlist-scraper

I've looked around and I tried executing the script like so:我环顾四周,并尝试像这样执行脚本:


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);
         }
    }

But I am not getting any output.但我没有得到任何 output。 What do I need to be able to run this specific script?我需要什么才能运行这个特定的脚本?

You can use like this:你可以这样使用:

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: Always copy your path from the file explorer tab Protip:始终从文件资源管理器选项卡中复制您的路径

And since you are getting JSON response try GSON library to parse it.并且由于您收到 JSON 响应,请尝试使用 GSON 库对其进行解析。

And if you want to work heavily on python using java, try exploring Jython如果您想使用 java 在 python 上大量工作,请尝试探索Jython

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM