199

Groovy 添加了使执行 shell 相当容易的execute方法;String

println "ls".execute().text

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

有类似的东西会很好;

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

7 回答 7

251

好的,自己解决了;

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: No such file or directory

于 2008-10-01T19:20:26.123 回答
60

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

有一个额外的方法Process允许您传递 aStringBuffer来检索文本:consumeProcessErrorStream(StringBuffer error).

例子:

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

println proc.text
println b.toString()
于 2008-10-01T19:16:06.960 回答
36
// 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()
}
于 2012-09-04T20:06:40.313 回答
32

我觉得这更惯用:

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"

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

于 2017-02-09T01:40:48.237 回答
26

要在上面提供的答案中添加一个更重要的信息 -

对于一个进程

def proc = command.execute();

总是尝试使用

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

而不是

def output = proc.in.text;

在 groovy 中执行命令后捕获输出,因为后者是阻塞调用(原因是 SO 问题)。

于 2014-08-16T06:08:39.850 回答
8
def exec = { encoding, execPath, execStr, execCommands ->

def outputCatcher = new ByteArrayOutputStream()
def errorCatcher = new ByteArrayOutputStream()

def proc = execStr.execute(null, new File(execPath))
def inputCatcher = proc.outputStream

execCommands.each { cm ->
    inputCatcher.write(cm.getBytes(encoding))
    inputCatcher.flush()
}

proc.consumeProcessOutput(outputCatcher, errorCatcher)
proc.waitFor()

return [new String(outputCatcher.toByteArray(), encoding), new String(errorCatcher.toByteArray(), encoding)]

}

def out = exec("cp866", "C:\\Test", "cmd", ["cd..\n", "dir\n", "exit\n"])

println "OUT:\n" + out[0]
println "ERR:\n" + out[1]
于 2016-09-22T03:09:58.100 回答
-5
command = "ls *"

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

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

于 2017-07-13T02:55:19.307 回答