How do I redirect output to stderr in groovy?

18,386

Solution 1

Just off the top of my head couldn't you do a bit of self-wiring:

def printErr = System.err.&println
printErr("AHHH")

but that is a bit manual

Solution 2

Groovy has access to the JRE:

System.err.println "goes to stderr"

Although there may be a more Groovy-fied way...

Solution 3

Another quite compact alternative is this:

System.err << "Want this to go to stderr"

Or you could add this at the top of your script

def err = System.err
...
err << "Want this to go to stderr"

which is what I'm now doing in my groovy shell scripts

Solution 4

If you just want something shorter to type, here are two options. First, you can import java.lang.System as anything you like, specifically something shorter like "sys":

import java.lang.System as sys
sys.err.println("ERROR Will Robinson")

Second, you can assign the System.err stream to a variable and use that variable from then on as an alias for System.err, like:

err = System.err
err.println("ERROR again Will Robinson")

This has the possible advantage that all the functions of System.err are accessible so you don't have to wire up each one individually (e.g. err.print, err.println, etc.).

Hopefully there is a standard Groovy way, because idiosyncratic renaming can be confusing to people who read your code.

Share:
18,386
timdisney
Author by

timdisney

CS grad student at UCSC. Studies programming languages. Made sweet.js.

Updated on July 01, 2022

Comments

  • timdisney
    timdisney almost 2 years

    I'm looking for a way to redirect output in a groovy script to stderr:

    catch(Exception e) {
        println "Want this to go to stderr"
    }
    
  • timdisney
    timdisney over 15 years
    Yep, I was hoping for a groovyish way.
  • sfussenegger
    sfussenegger about 14 years
    It's even possible to redefine println: (def println = System.err.&println) - useful at the beginning of a script that writes results to stdout by something like foo.write(System.in)
  • Matthias Braun
    Matthias Braun over 7 years
    This throws a MissingMethodException if used with a GString. For example this doesn't work: printErr "Problem with: $aVariable"
  • codeLes
    codeLes over 7 years
    As this answer is likely grossly outdated, I have made it community editable.
  • Stefan van den Akker
    Stefan van den Akker over 6 years
    @MatthiasBraun I can't reproduce your error on 2.4.12: it works with GStrings.