Groovy는 쉘 실행을 상당히 쉽게 만드는 execute
방법을 추가합니다 String
.
println "ls".execute().text
그러나 오류가 발생하면 결과 출력이 없습니다. 표준 오류와 표준을 모두 쉽게 얻을 수있는 방법이 있습니까? (다발의 코드를 만드는 것; 두 개의 스레드를 만들어 두 입력 스트림을 모두 읽은 다음 부모 스트림을 사용하여 완료 될 때까지 기다렸다가 문자열을 다시 텍스트로 변환 하시겠습니까?)
다음과 같은 것이 좋습니다.
def x = shellDo("ls /tmp/NoFile")
println "out: ${x.out} err:${x.err}"
답변
좋아, 스스로 해결했다.
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
표시합니다 :
out> err> ls: cannot access /badDir: No such file or directory
답변
"ls".execute()
작동 하는 Process
객체를 반환 "ls".execute().text
합니다. 오류 스트림을 읽고 오류가 있는지 판별 할 수 있어야합니다.
텍스트를 검색하기 위해 Process
a StringBuffer
를 전달할 수 있는 추가 방법이 있습니다 consumeProcessErrorStream(StringBuffer error)
..
예:
def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)
println proc.text
println b.toString()
답변
// 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"
다른 게시물에서 언급했듯이, 이들은 호출을 차단하지만 출력 작업을 원하므로 이것이 필요할 수 있습니다.
답변
위에 제공된 답변에 하나 이상의 중요한 정보를 추가하려면-
프로세스
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 질문 ).
답변
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]
답변
command = "ls *"
def execute_state=sh(returnStdout: true, script: command)
그러나 명령이 실패하면 프로세스가 종료됩니다.