简体   繁体   English

Java ProcessBuilder 无法在 Java 中运行 Python 脚本

[英]Java ProcessBuilder not able to run Python script in Java

null from bfr.readLine()来自bfr.readLine() null

However, there is no problem if I run the python file directly on terminal by firing:但是,如果我通过触发直接在终端上运行 python 文件,则没有问题:

python C:/Machine_Learning/Text_Analysis/Ontology_based.py python C:/Machine_Learning/Text_Analysis/Ontology_based.py

The last line in my Python script is >> print(data)我的 Python 脚本的最后一行是>> print(data)

The result of the following code is:以下代码的结果是:

Running Python starts:运行 Python 开始:

First Line: null第一行:空

Picked up _JAVA_OPTIONS: -Xmx512M拿起_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.通常在使用ProcessBuilder执行命令时,不会考虑PATH变量。 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.你的python C:/Machine_Learning/Text_Analysis/Ontology_based.py直接在你的 CMD shell 中工作,因为它可以使用PATH变量定位python可执行文件。 Please provide the absolute path to python command in your Java code.请在您的 Java 代码中提供python命令的绝对路径。 In below code replace <Absolute Path to Python> with the path to python command and its libraries.在下面的代码中,将<Absolute Path to Python>替换为python命令及其库的路径。 Usually it will something like C:\\Python27\\python in Windows by default通常它会在 Windows 中默认类似于C:\\Python27\\python

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.执行 Process#waitFor 并查看exitValue是什么。 If it isn't 0 then it's highly probable that your script is dying.如果它不是 0,那么您的脚本很可能正在死亡。

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.确保从 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.此脚本使用 Java 中的参数运行 python 文件。 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);
        }
    }
  }

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

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