Programing

쉘 명령을 실행하는 Groovy

crosscheck 2020. 6. 4. 18:58
반응형

쉘 명령을 실행하는 Groovy


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합니다. 오류 스트림을 읽고 오류가 있는지 판별 할 수 있어야합니다.

텍스트를 검색하기 위해 Processa 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()
}

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

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

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).


I find this more idiomatic:

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"

As another post mentions, these are blocking calls, but since we want to work with the output, this may be necessary.


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)

but if the command failure the process will terminate

참고URL : https://stackoverflow.com/questions/159148/groovy-executing-shell-commands

반응형