2012-05-21 8 views

risposta

7

È possibile utilizzare waitForProcessOutput che prende due Appendables (docs here)

def process = "ls -l".execute() 
def (output, error) = new StringWriter().with { o -> // For the output 
    new StringWriter().with { e ->      // For the error stream 
    process.waitForProcessOutput(o, e) 
    [ o, e ]*.toString()        // Return them both 
    } 
} 
// And print them out... 
println "OUT: $output" 
println "ERR: $error" 
+0

Accetterò la tua risposta perché è il più conciso finora. Mi chiedo perché non ci sia un 'process.error'. – ripper234

+2

principalmente perché l'utilizzo del membro .text è pericoloso. Se il testo in uscita nei flussi di output o di errore supera il buffer, il processo si arresterà fino a quando non verrà letto il flusso. In realtà è una buona idea quando non si sa quanto tempo sarà l'output (che di solito è il caso degli errori) per usare un thread separato per catturare il flusso. – billjamesdev

+0

+1 per il commento @BillJames. Per inciso, questo è ciò che ['waitForProcessOutput' fa] (https://github.com/groovy/groovy-core/blob/master/src/main/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L206) (crea due thread per ascoltare l'output) –

0

Sulla base di tim_yates risposta, ho provato su Jenkins e trovato questo problema con assegnazione multipla: https://issues.jenkins-ci.org/browse/JENKINS-45575

Quindi questo funziona ed è è anche conciso:

def process = "ls -l".execute() 
def output = new StringWriter(), error = new StringWriter() 
process.waitForProcessOutput(output, error) 
println "exit value=${process.exitValue()}" 
println "OUT: $output" 
println "ERR: $error"