英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论