在Groovy中收集执行外部命令的输出的差异 [英] Difference in collecting output of executing external command in Groovy

查看:143
本文介绍了在Groovy中收集执行外部命令的输出的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def(下面的代码被卡住了(我认为它阻止了I / O)静态executeCurlCommand(URL){
def url =curl+ URL;
def proc = url.execute();
def output = proc.in.text;
返回输出;
}

但是,当我将代码更改为

  def static executeCurlCommand(URL){
def url =curl+ URL;
def proc = url.execute();
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream,System.err)
return outputStream.toString();
}

每次都能正常工作。我无法理解为什么第一种方式即通过 proc.in.text 输入会挂起一段时间?当我在Windows上以及cygwin上试过时,并没有看到特定于环境的问题。



为了测试/运行上面的方法,我试过了 -

  public static void main(def args){
def url ='http://mail.google.com';
println(Output:+ executeCurlCommand(url));
}

我在SO上看到了很多问题,都提供了第二种方法。虽然它运作良好,但我希望我能知道第一种方法有什么问题吗?有没有人曾经遇到过这种情况?

解决方案

第一种方法填充缓冲区,然后阻止等待更多空间来输出第二种方法在进程运行时通过一个单独的线程从缓冲区输出流,所以进程不会阻塞。



b

Following code gets stuck(which I think is blocking I/O) many times (works some time).

def static executeCurlCommand(URL){
    def url = "curl " + URL;
    def proc = url.execute();
    def output = proc.in.text;
    return output;
}

But when I changes the code to

def static executeCurlCommand(URL){
    def url = "curl " + URL;
    def proc = url.execute();
    def outputStream = new StringBuffer();
    proc.waitForProcessOutput(outputStream, System.err)
    return outputStream.toString(); 
}

it works fine every time. I am not able to understand why does the 1st way i.e taking input by proc.in.text hangs some time? Does not look an environment specific problem as I tried it on Windows as well as cygwin.

To test/run the above method I have tried -

public static void main(def args){
    def url = 'http://mail.google.com';
    println("Output : " + executeCurlCommand(url));
}   

I have seen multiple questions on SO and all provide the 2nd approach. Although it works good I wish I could know whats wrong with 1st approach ? Has anyone has encountered this scenario before?

解决方案

The first approach fills a buffer up and then blocks waiting for more room to write output to.

The second approach streams output from the buffer via a separate thread as the process is running, so the process doesn't block.

这篇关于在Groovy中收集执行外部命令的输出的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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