How to run command line commands in a compiled Gradle plugin?

John Sardinha :

How can you execute a CMD command from a Gradle task without the Gradle DSL (commandLine 'echo', ':)'), i.e. something like:

open class MyTask : DefaultTask() {

    @TaskAction
    fun task() {
        Runtime.getRuntime().exec("echo :)") //Doesn't print anything
    }

}
itwasntme :

Nothing is printed, because the exec method executes given command in a new process, separate to the process handling Gradle task (and has its own I/O streams).

The exec method returns the Process object. Citing docs, the Process "provides control of native processes started by ProcessBuilder.start and Runtime.exec".

So, to capture the output of executed command, it's required to read it from the process of that command.

The simple example of printing output from echo :) could be:

task something {
    doLast {
        Process echo = Runtime.getRuntime().exec("cmd /c echo :)")
        println new BufferedReader(new InputStreamReader(echo.getInputStream())).readLine()
    }
}

(I'm having cmd /c command prefix, because of the Windows OS)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25329&siteId=1