2014-03-06 34 views
0

我有以下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中實現這一點?

回答

1

至於我自己的經驗,爲了確保Python腳本的輸出沒有被緩衝,除了DNA建議的內容外,還需要禁用輸出緩衝。所以一定要給解釋器打上-u的標誌,也可能需要sys.stdout.flush()可能

欲瞭解更多信息,請參閱Disable output buffering或只是谷歌「蟒蛇輸出緩衝」或「蟒蛇禁用輸出緩衝」。

1

您需要打印出從Python程序輸出的每一行,而不是(或者以及)追加它ret

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