简体   繁体   中英

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 .

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. 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

And since you are getting JSON response try GSON library to parse it.

And if you want to work heavily on python using java, try exploring Jython

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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