简体   繁体   中英

Java ProcessBuilder not able to run Python script in Java

null from bfr.readLine()

However, there is no problem if I run the python file directly on terminal by firing:

python C:/Machine_Learning/Text_Analysis/Ontology_based.py

The last line in my Python script is >> print(data)

The result of the following code is:

Running Python starts:

First Line: null

Picked up _JAVA_OPTIONS: -Xmx512M


package text_clustering;

import java.io.*;

public class Similarity {

    /**
     * 
     * @param args
     * 
     */
    public static void main(String[] args){
        try{
            String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
            //String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
            ProcessBuilder pb = new ProcessBuilder("python", pythonPath);
            Process p = pb.start();
            
            BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            System.out.println("Running Python starts: " + line);
            line = bfr.readLine();
            System.out.println("First Line: " + line);
            while ((line = bfr.readLine()) != null){
                System.out.println("Python Output: " + line);
                
                
            }

        }catch(Exception e){System.out.println(e);}
    }

}

Usually when executing commands using ProcessBuilder , PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\\Python27\\python in Windows by default

package text_clustering;

import java.io.*;

public class Similarity {

    /**
     * 
     * @param args
     * 
     */
    public static void main(String[] args){
        try{
            String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
            //String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
            ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
            Process p = pb.start();

            BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            System.out.println("Running Python starts: " + line);
            int exitCode = p.waitFor();
            System.out.println("Exit Code : "+exitCode);
            line = bfr.readLine();
            System.out.println("First Line: " + line);
            while ((line = bfr.readLine()) != null){
                System.out.println("Python Output: " + line);


            }

        }catch(Exception e){System.out.println(e);}
    }

}

Reading from stdin returns null when the script is killed/dies. Do a Process#waitFor and see what the exitValue is. If it isn't 0 then it's highly probable that your script is dying.

I'd try making it work with a dumb script that only writes a value. Make sure that you print all error information from python.

try {

    Process p = Runtime.getRuntime().exec(
            "python   D://input.py   ");
    BufferedReader in = new BufferedReader(new InputStreamReader(
            p.getInputStream()));

    String line;  
        while ((line = in.readLine()) != null) {  
            System.out.println(line);  
        }  
        in.close();
        p.waitFor();



} catch (Exception e) {
}
try {
    ProcessBuilder pb = new ProcessBuilder("C:/Python27/python", "D://searchTestJava//input.py");
    Process p = pb.start();
    BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));

    System.out.println(".........start   process.........");
    String line = "";
    while ((line = bfr.readLine()) != null) {
        System.out.println("Python Output: " + line);
    }

    System.out.println("........end   process.......");

} catch (Exception e) {
    System.out.println(e);
}

I tried this one. This script runs a python file with the argument in Java. It also logs about which line, your program is executing. Hope this Helps.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;

    public class Test {
      public static void main(String... args) throws IOException {

        ProcessBuilder pb =
                new ProcessBuilder("python","samples/test/table_cv.py","1.pdf");

        pb.redirectErrorStream(true);
        Process proc = pb.start();

        Reader reader = new InputStreamReader(proc.getInputStream());
        BufferedReader bf = new BufferedReader(reader);
        String s;
        while ((s = bf.readLine()) != null) {
            System.out.println(s);
        }
    }
  }

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