捕获python命令的输出

时间:2014-03-06 16:55:20

标签: java python

我有以下python脚本

#!/usr/bin/env python
import subprocess
import sys
from time import sleep
p = subprocess.Popen(["ls", "-l", "."], stdout=subprocess.PIPE)
output, err = p.communicate()
print "*** Running ls -l command ***\n", output

print "I'm gonna wait 1 second"
sleep(1)

print "Waited..."

sleep(5)

print "Finished"

以下执行该脚本的Java程序:

protected List<String> runOutputLinesCommand(String scriptsPath) {
    List<String> ret = new ArrayList<String>();

    // constructs the python command to be executed
    String cmd = scriptsPath
            + COMMAND;
    ProcessBuilder pb = new ProcessBuilder(cmd);

    pb.redirectErrorStream(true);
    try {
        // executes the command and waits for its interruption
        Process p = pb.start();
        String s;
        // read from the process's combined stdout & stderr
        BufferedReader stdout = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        while ((s = stdout.readLine()) != null) {
            // appends the output of the command to the ret variable
            ret.add(s.trim());
        }
        p.waitFor();
        p.getInputStream().close();
        p.getOutputStream().close();
        p.getErrorStream().close();
    } catch (InterruptedException ex) {
        ret.add("script interrupted: " + ex);
    } catch (IOException ex) {
        ret.add("IOException: " + ex);
        ex.printStackTrace(System.out);
    } catch (Exception ex) {
        ret.add("Exception: " + ex);
        ex.printStackTrace(System.out);
    }

    return ret;
}

我想要的是java程序打印实时执行的python行,而不是在执行所有脚本之前。我希望Java程序在发生时打印python脚本的输出。我怎样才能在java中实现这个目标?

2 个答案:

答案 0 :(得分:1)

您需要打印出Python程序的每一行输出,而不是(或同样)将其附加到ret

    while ((s = stdout.readLine()) != null) {
        //ret.add(s.trim());
        System.out.println(s);
    }

答案 1 :(得分:1)

就我的经验而言,为了确保Python脚本的输出没有缓冲,除了DNA建议之外,还需要禁用输出缓冲。因此,请务必使用-u标志调用脚本到解释器;另外,sys.stdout.flush() 可能是必要的。

有关详细信息,请参阅例如Disable output buffering或只是google“python output buffering”或“python disable output buffering”。

相关问题