【问题标题】:Println as argument in groovy scriptPrintln 作为 groovy 脚本中的参数
【发布时间】:2012-01-24 15:29:03
【问题描述】:

我有一个打印一些统计数据的 groovy 脚本:println: "..."

现在我有另一个需要这些数据的 groovy 脚本。是否有可能以某种方式从第二个脚本运行第一个脚本并将此数据保存为参数,然后从第二个脚本使用它们?我只知道如何运行脚本:使用GroovyShell() 然后run(...) 但这不会返回第一个脚本的输出

【问题讨论】:

    标签: groovy


    【解决方案1】:

    几个选项:

    1. 如果您从脚本中调用它,请重新定义 stdout
    2. 修复第一个脚本,使其打印从类中检索到的数据,并重新编写调用脚本以使用该类,而不是依赖于第一个的打印输出。长期可能是最好的选择。
    3. 在命令行上使用管道: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
    

    【讨论】:

    • thx 很多 3. 我将使用最后一种方法,但我必须将您的 while 块中的条件更改为 (( line = r.readLine() ) != null) 因为在我的输出中只是 println然后这个循环停止。
    【解决方案2】:

    一种方法是在调用第一个脚本时在绑定中设置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...

    【讨论】:

    • 我认为你是对的!我不敢相信你只是重写了 s1.groovy 和 s2.groovy。
    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 2019-05-03
    • 2020-12-24
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多