groovy脚本中Println作为参数

groovy脚本中Println作为参数,groovy,Groovy,我有一个groovy脚本可以打印一些统计信息:println: 现在我有了另一个groovy脚本,它需要这些数据。是否可以从第二个脚本运行第一个脚本并将此数据保存为paramater,然后从第二个脚本使用它们?我只知道如何运行脚本:使用GroovyShell,然后运行。。。但这不会返回第一个脚本的输出。有几个选项: 如果您是从脚本调用它,请重新定义stdout。 修复第一个脚本,使其打印从类检索的数据,并重新编写调用脚本以使用该类,而不是依赖第一个脚本打印的输出。长期可能是最好的选择。 在命令行

我有一个groovy脚本可以打印一些统计信息:println:

现在我有了另一个groovy脚本,它需要这些数据。是否可以从第二个脚本运行第一个脚本并将此数据保存为paramater,然后从第二个脚本使用它们?我只知道如何运行脚本:使用GroovyShell,然后运行。。。但这不会返回第一个脚本的输出。有几个选项:

如果您是从脚本调用它,请重新定义stdout。 修复第一个脚本,使其打印从类检索的数据,并重新编写调用脚本以使用该类,而不是依赖第一个脚本打印的输出。长期可能是最好的选择。 在命令行上使用管道:groovy s1.groovy | groovy s2.groovy 就个人而言,在编写使用stdin/stdio的东西时,我更喜欢最后一种方法。例如:

s1.groovy

s2.groovy

输出

有几个选择:

如果您是从脚本调用它,请重新定义stdout。 修复第一个脚本,使其打印从类检索的数据,并重新编写调用脚本以使用该类,而不是依赖第一个脚本打印的输出。长期可能是最好的选择。 在命令行上使用管道:groovy s1.groovy | groovy s2.groovy 就个人而言,在编写使用stdin/stdio的东西时,我更喜欢最后一种方法。例如:

s1.groovy

s2.groovy

输出


一种方法是在调用第一个脚本时在绑定中设置out参数:

因此,给定一个脚本s1.groovy:

我们可以在s2.groovy中使用

然后用groovys2.groovy运行它

编辑
我认为这是Dave回答中的选项1…

一种方法是在调用第一个脚本时在绑定中设置out参数:

因此,给定一个脚本s1.groovy:

我们可以在s2.groovy中使用

然后用groovys2.groovy运行它

编辑
我认为这是戴夫回答中的选项1…

我认为你是对的!我不敢相信你只是随意重写了s1.groovy和s2.groovy。我想你是对的!我真不敢相信你刚刚重写了s1.groovy和s2.groovy willy-nilly.thx很多3。我将使用最后一种方法,但我必须将while块中的条件更改为line=r.readLine!=null,因为在我的输出中只是println,然后这个循环就停止了。我将使用最后一种方法,但我必须将while块中的条件更改为line=r.readLine!=null,因为在我的输出中只是println,然后这个循环停止。
5.times { println it }
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
//Print the letters of 'tim_yates', one per line
'tim_yates'.each this.&println
// 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