java 如何在 groovy 中将输出重定向到 stderr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/381920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:10:45  来源:igfitidea点击:

How do I redirect output to stderr in groovy?

javascriptinggroovy

提问by timdisney

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

我正在寻找一种将 groovy 脚本中的输出重定向到 stderr 的方法:

catch(Exception e) {
    println "Want this to go to stderr"
}

采纳答案by codeLes

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

但这有点手动

回答by James Frost

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

这就是我现在在我的 groovy shell 脚本中所做的

回答by Dan Vinton

Groovy has access to the JRE:

Groovy 可以访问 JRE:

System.err.println "goes to stderr"

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

虽然可能有一种更加 Groovy 的方式......

回答by Dan Vinton

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":

如果您只想输入更短的内容,这里有两个选项。首先,您可以将 java.lang.System 导入为您喜欢的任何内容,特别是诸如“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:

其次,您可以将 System.err 流分配给一个变量,然后将该变量用作 System.err 的别名,例如:

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.).

这有一个可能的优点,即 System.err 的所有功能都可以访问,因此您不必单独连接每个功能(例如 err.print、err.println 等)。

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

希望有一种标准的 Groovy 方式,因为特殊的重命名可能会让阅读您代码的人感到困惑。