Groovy - Shell Scripting - 无法进行通信

时间:2017-08-29 13:27:12

标签: java bash macos shell groovy

我是Groovy的新手,并尝试编写一个shell脚本,让我自动执行命令行任务。

这是手动方式。 我打开终端,使用一个命令,它不会立即响应,但过了一段时间,然后该命令问几个问题,我回答y / n等,然后我得到最终的结果。

现在我想编写一个groovy shell脚本,让我使用ProcessBuilder,然后发送一个命令,获取输出,并根据输出写入第二个命令,并重复此过程,直到过程完成。

我尝试编写以下脚本,但是发生的事情是我能够触发第一个命令,但它不会等我提供输入并继续。

请告知我应该在我的代码中做出哪些更改以等待它在我发送first_command之后从我的代码中获取输入。

#!/usr/bin/env groovy

String workingDir = System.console().readLine 'Working Directory?';
workingDir = workingDir.trim();

if (!workingDir?.trim()) {
  workingDir = "/Volumes/BOOTCAMP/Automation/test";
}

println "Your working directory is $workingDir";

Boolean isDone = false;
Boolean canMove = false;

ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash");
processBuilder.directory(new File(workingDir));
processBuilder.redirectErrorStream(true);

Process proc = processBuilder.start();
Scanner scannr = new Scanner(proc.getInputStream());

new Thread() {
    public void run() {
      while(true){
        while (scannr.hasNextLine()){
          println scannr.nextLine();
        }
        if(isDone){
          break; 
        }
      }
    }
}.start();

PrintWriter writer = new PrintWriter(proc.getOutputStream());
new Thread() {
    public void run() {
        while (isDone == false){
          if(canMove == false){
            canMove = true;

            // Write a few commands to the program.
            writer.println("first_command");
            writer.flush();
          }
        }

        if(isDone){
          writer.close();
        }
    }
}.start();

1 个答案:

答案 0 :(得分:0)

java.lang.Process

的groovy扩展中有很多waitXXX函数

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Process.html

如果流程的输出不大,则执行示例:

Process p = "cmd /c dir c:\\".execute() //you can use BrocessBuilder here
def txt = p.with{
    def output = new StringWriter()
    def error = new StringWriter()
    //wait for process ended and catch stderr and stdout 
    it.waitForProcessOutput(output, error)
    //check there is no error
    assert error.toString().size()==0: "$error"
    //assert it.exitValue()==0 //we can do check with error code
    //return stdout from closure 
    return output.toString()
}