2013年1月30日水曜日

Gradleで実行したコマンドの標準出力を文字列として取得する

Gradleで実行したコマンドラインのコマンドからの標準出力を、文字列として取得する方法は、以下の通り。

ant.condition(property: "os", value: "windows") { os(family: "windows") }
ant.condition(property: "os", value: "unix" ) { os(family: "unix") }
task execCommandLine(type:Exec) {
switch(ant.properties.os){
case 'windows':
commandLine 'cmd', '/c', 'echo', 'hello'
break
case 'unix':
commandLine 'echo', 'hello'
break
}
standardOutput = new ByteArrayOutputStream()
}
execCommandLine.doFirst {
println 'doFirst'
print standardOutput.toString()
}
execCommandLine << {
println 'doLast'
print standardOutput.toString()
}
view raw build.gradle hosted with ❤ by GitHub

標準出力をByteArrayOutputStreamに割り当て(13行目)、コマンド実行後にそのByteArrayOutputStreamから文字列を取得している(23行目)。

上記のタスクを実行した結果は以下の通り。
$ gradle -q execCommandLine
doFirst
doLast
hello

当たり前だが、コマンド実行時に出力される文字列は、コマンドの実行後でないと取得できない。

0 件のコメント:

コメントを投稿