Groovy将execute方法添加到String中,使执行shell变得相当容易;

println "ls".execute().text

但是如果发生错误,则不会产生输出。是否有一种简单的方法可以同时得到标准错误和标准?(除了创建一堆代码来;创建两个线程来读取两个输入流,然后使用父流等待它们完成,然后将字符串转换回文本?)

如果能有这样的东西就好了;

 def x = shellDo("ls /tmp/NoFile")
 println "out: ${x.out} err:${x.err}"

当前回答

// a wrapper closure around executing a string                                  
// can take either a string or a list of strings (for arguments with spaces)    
// prints all output, complains and halts on error                              
def runCommand = { strList ->
  assert ( strList instanceof String ||
           ( strList instanceof List && strList.each{ it instanceof String } ) \
)
  def proc = strList.execute()
  proc.in.eachLine { line -> println line }
  proc.out.close()
  proc.waitFor()

  print "[INFO] ( "
  if(strList instanceof List) {
    strList.each { print "${it} " }
  } else {
    print strList
  }
  println " )"

  if (proc.exitValue()) {
    println "gave the following error: "
    println "[ERROR] ${proc.getErrorStream()}"
  }
  assert !proc.exitValue()
}

其他回答

我觉得这个更地道:

def proc = "ls foo.txt doesnotexist.txt".execute()
assert proc.in.text == "foo.txt\n"
assert proc.err.text == "ls: doesnotexist.txt: No such file or directory\n"

正如另一篇文章提到的,这些是阻塞调用,但由于我们想要处理输出,这可能是必要的。

command = "ls *"

def execute_state=sh(returnStdout: true, script: command)

但是如果命令失败,进程将终止

"ls".execute()返回一个Process对象,这就是为什么"ls".execute()。文字作品。您应该能够读取错误流,以确定是否有任何错误。

Process上有一个额外的方法,允许您传递一个StringBuffer来检索文本:consumeProcessErrorStream(StringBuffer错误)。

例子:

def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)

println proc.text
println b.toString()

我自己解出来的;

def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"

显示:

out> err> ls: cannot access /badDir:没有这样的文件或目录

// a wrapper closure around executing a string                                  
// can take either a string or a list of strings (for arguments with spaces)    
// prints all output, complains and halts on error                              
def runCommand = { strList ->
  assert ( strList instanceof String ||
           ( strList instanceof List && strList.each{ it instanceof String } ) \
)
  def proc = strList.execute()
  proc.in.eachLine { line -> println line }
  proc.out.close()
  proc.waitFor()

  print "[INFO] ( "
  if(strList instanceof List) {
    strList.each { print "${it} " }
  } else {
    print strList
  }
  println " )"

  if (proc.exitValue()) {
    println "gave the following error: "
    println "[ERROR] ${proc.getErrorStream()}"
  }
  assert !proc.exitValue()
}