执行时保留颜色代码 [英] Preserve color codes when exec-ing

查看:127
本文介绍了执行时保留颜色代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为大型程序的一部分,我正在调用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()

如果我直接从终端对grep进行相同的调用,则grep将输出多色文本(例如,以红色突出显示其输出中的任何匹配项)。做一些研究,似乎有一些特殊的 ansi颜色代码其他程序用来更改颜色突出显示。

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.

当我执行go命令时,这些颜色在哪里?有什么方法可以执行,以保留ansi颜色代码,然后将grep的输出复制到标准输出(类似于

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

(我也知道我可以手动重新插入颜色代码。但这似乎很痛苦,我宁愿只管grep的原始颜色。)

(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!

推荐答案

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.

您可以强制使用 grep 输出颜色>-color = always 标记。

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

这篇关于执行时保留颜色代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆