Groovy将execute方法添加到String中,使执行shell变得相当容易;
println "ls".execute().text
但是如果发生错误,则不会产生输出。是否有一种简单的方法可以同时得到标准错误和标准?(除了创建一堆代码来;创建两个线程来读取两个输入流,然后使用父流等待它们完成,然后将字符串转换回文本?)
如果能有这样的东西就好了;
def x = shellDo("ls /tmp/NoFile")
println "out: ${x.out} err:${x.err}"
在以上提供的答案中添加一个更重要的信息-
对于流程来说
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中执行命令后捕获输出,因为后者是一个阻塞调用(因此存在问题)。
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]
在以上提供的答案中添加一个更重要的信息-
对于流程来说
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中执行命令后捕获输出,因为后者是一个阻塞调用(因此存在问题)。