Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture process output in Groovy

Tags:

groovy

I have a Groovy script that recurses through a directory looking for .png files, and invokes pngquant (a command-line utility) on each of. The output of pngquant should be printed on the terminal. The relevant code is:

def command = "pngquant -f -ext .png"

root.eachFileRecurse(groovy.io.FileType.FILES) {File file ->

    if (file.name.endsWith('.png')) { 
        println "Compressing file: $file"

        def imgCommand = "$command $file.absolutePath"

        Process pngquantCmd = imgCommand.execute()
        pngquantCmd.consumeProcessOutput(System.out, System.err)        
    }
}

The script works fine, but once all the files have been processed, it seems that stout is still being redirected, because the command-prompt never appears unless I kill the process with Ctrl + C. Do I need to somehow "undo"

pngquantCmd.consumeProcessOutput(System.out, System.err)        

or is there a better way to redirect the output of this process to the console? I guess I could solve this problem simply by adding System.exit(0), but this doesn't seem like the right solution. The problem only occurs on Linux.

like image 477
Dónal Avatar asked Jul 20 '12 12:07

Dónal


2 Answers

Instead of

    pngquantCmd.consumeProcessOutput(System.out, System.err)        

Which will start a couple of threads to read the outputs and plough on regardless of the process' situation, you should try

    pngquantCmd.waitForProcessOutput(System.out, System.err)

Which will redirect the process output and then wait for it to finish before moving on :-)

like image 149
tim_yates Avatar answered Sep 22 '22 10:09

tim_yates


You can also do

Process pngquantCmd = imgCommand.execute();
def output= pngquantCmd.text;
println("Output : " + output);
like image 39
Aniket Thakur Avatar answered Sep 25 '22 10:09

Aniket Thakur