【发布时间】:2012-01-24 15:29:03
【问题描述】:
我有一个打印一些统计数据的 groovy 脚本:println: "..."
现在我有另一个需要这些数据的 groovy 脚本。是否有可能以某种方式从第二个脚本运行第一个脚本并将此数据保存为参数,然后从第二个脚本使用它们?我只知道如何运行脚本:使用GroovyShell() 然后run(...) 但这不会返回第一个脚本的输出
【问题讨论】:
标签: groovy
我有一个打印一些统计数据的 groovy 脚本:println: "..."
现在我有另一个需要这些数据的 groovy 脚本。是否有可能以某种方式从第二个脚本运行第一个脚本并将此数据保存为参数,然后从第二个脚本使用它们?我只知道如何运行脚本:使用GroovyShell() 然后run(...) 但这不会返回第一个脚本的输出
【问题讨论】:
标签: groovy
几个选项:
stdout。groovy s1.groovy | groovy s2.groovy
就个人而言,在编写与 stdin/stdio 相关的内容时,我更喜欢最后一种方法。示例:
s1.groovy
5.times { println it }
s2.groovy
r = new BufferedReader(new InputStreamReader(System.in))
while (l = r.readLine()) { println((l as Integer) * 2) }
输出
$ groovy s1.groovy
0
1
2
3
4
$ groovy s1.groovy | groovy s2.groovy
0
2
4
6
8
【讨论】:
一种方法是在调用第一个脚本时在绑定中设置out 参数:
所以给定一个脚本s1.groovy:
//Print the letters of 'tim_yates', one per line
'tim_yates'.each this.&println
我们可以做(s2.groovy)
// Create a StringWriter that will capture output
String output = new StringWriter().with { sw ->
// And make a Binding for our script
new Binding().with { b ->
// Set 'out' in the Binding to be our StringWriter
b[ 'out' ] = sw
// evaluate the file with the GroovyShell (using the binding)
new GroovyShell( b ).evaluate( new File( 's1.groovy' ) )
}
// And return the String captured in our writer
sw.toString()
}
println output
然后用groovy s2.groovy运行它
我认为这是 Dave 回答中的选项 #1...
【讨论】: