在执行时保留颜色代码

huangapple go评论84阅读模式
英文:

Preserve color codes when exec-ing

问题

作为一个更大程序的一部分,我正在调用grep,并将其结果输出到标准输出:

// 执行grep命令
cmd := exec.Command(GREP_BIN_PATH, argArray...)
stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Fatal(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
    log.Fatal(err)
}

err = cmd.Start()
if err != nil {
    log.Fatal(err)
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
cmd.Wait()

如果我直接从终端调用相同的grep命令,grep会输出多彩的文本(例如,将输出中的匹配项以红色进行高亮显示)。经过一些研究,似乎grep/其他程序使用特殊的ANSI颜色代码来改变颜色高亮显示。

当我从go中执行命令时,这些颜色会去哪里?有没有办法在go中执行命令时保留ANSI颜色代码,并将grep的输出复制到标准输出(类似于这里的帖子,但是针对go)?

(我也知道我可以手动重新插入颜色代码。但那似乎很麻烦,我宁愿只是将grep的原始颜色输出。)

如果问题中有什么不清楚或需要澄清的地方,请告诉我。谢谢!

英文:

As part of a larger program, I'm making a call to grep, and outputting its results to standard out:

// execute grep command
cmd := exec.Command(GREP_BIN_PATH, argArray...)
stdout, err := cmd.StdoutPipe()
if err != nil {
	log.Fatal(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
	log.Fatal(err)
}

err = cmd.Start()
if err != nil {
	log.Fatal(err)
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
cmd.Wait()

If I make an identical call to grep directly from the terminal, grep outputs multi-color text (eg., highlighting in red any match in its output). Doing a little research, it seems as though there are special ansi color codes that grep/other programs use to change color highlighting.

Where do these colors go when I exec a command from go? Is there any way that I can exec from within go to preserve ansi color codes and just copy the output from grep to standard out (similar to the post here, but for go)?

(I also know that I could manually re-insert color codes. But that seems painful, and I'd rather just pipe grep's original colors.)

Please let me know if something in the question is unclear/needs clarification. Thanks!

答案1

得分: 8

grep和大多数其他使用颜色的工具在决定是否使用颜色时会检测它们是否将输出发送到终端。

文件、管道等通常不需要颜色代码,并且不知道如何处理它们。

但是,你可以使用--color=always标志强制grep输出颜色。

英文:

grep and most other color-using tools detect whether they are sending output to a terminal or not when they decide whether to use color.

Files and pipes, etc. often don't want the color codes and don't know what to do with them.

You can force grep to output colors anyway with the --color=always flag though.

huangapple
  • 本文由 发表于 2015年4月1日 01:54:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/29375241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定