捕获Groovy中的进程输出 [英] capture process output in Groovy

查看:507
本文介绍了捕获Groovy中的进程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Groovy脚本,通过查找.png文件的目录递归,并调用 pququant (一个命令行脚本,线实用程序)上的每个。 pngquant的输出应打印在终端上。相关的代码是:

  def command =pngquant -f -ext .png

root .eachFileRecurse(groovy.io.FileType.FILES){文件文件 - >

if(file.name.endsWith('。png')){
println压缩文件:$ file

def imgCommand =$ command $ file.absolutePath

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

这个脚本可以正常工作,但是一旦所有文件都被处理完毕,看起来stout仍然被重定向,因为除非我用 Ctrl + C 终止进程,否则命令提示符不会出现。我需要以某种方式撤消

pre $ c pre $ $ $ pngquantCmd.consumeProcessOutput($ System.out,System.err)

code>

或者有更好的方法将此进程的输出重定向到控制台吗?我想我可以通过简单地添加 System.exit(0)来解决这个问题,但这看起来不是正确的解决方案。这个问题只发生在Linux上。

解决方案

而不是

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

其中将启动一些线程来读取输出和犁,而不管进程的情况如何,您应该尝试

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

这将重定向进程输出,然后等待它完成前继续: - )


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.

解决方案

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 :-)

这篇关于捕获Groovy中的进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆