Thursday, December 8, 2016

Executing command-line using Groovy

Running command-line executions through Groovy may at first seem straight-forward. But after thoroughly stepping through a real world example, I've found the need to write up a function  that will make this process a little easier, as shown in the code below:


      /**  
       * Execute on the command line  
       * @param command  
       * @return  
       */  
      private String execCommand(Object command, OutputStream os=null, Boolean doLog = true, Boolean ignoreStdErr = false) {  
           boolean doReturn = false  
           if (os == null) {  
                os = new ByteArrayOutputStream()  
                doReturn = true  
           }  
           ByteArrayOutputStream serr = new ByteArrayOutputStream()  
           if (doLog) {  
                logger.info("Running command: "+command)  
           }  
           Process p = command.execute()  
           p.consumeProcessOutput(os, serr)  
           p.waitFor()            
           //p.waitForProcessOutput()  
           //p.waitForOrKill(30000)  
           if (! ignoreStdErr && serr.size() > 0) {  
                logger.error(serr.toString())  
                throw new Exception(serr.toString())  
           }  
           if (doReturn)  
                return new String(os.toString())  
           else  
                return null  
      }  

No comments:

Post a Comment