【问题标题】:How to read a command output with its color attributes?如何读取带有颜色属性的命令输出?
【发布时间】:2019-02-01 09:15:57
【问题描述】:

是否可以读取带有颜色属性的命令输出。我的意思是,我们可以阅读实际的转义序列吗?

例如; 命令输出为红色:

Hello

我想把它读成:

\033[31;1;4mHello\033[0m

目前我正在阅读它:

func stat(hash string) string {
    cmd := exec.Command("git", "show", "--stat", hash)
    out, err := cmd.Output()
    if err != nil {
        return err.Error()
    }
    return string(out)
}

【问题讨论】:

  • 你是如何读取命令输出的?你试过什么?显示您的代码。您遇到了什么问题?
  • 请注意,许多命令会尝试巧妙地检测它们是否正在打印到终端,然后只打印颜色。因此,如果您将它们的输出重定向到其他地方,则那里可能没有 ANSI 转义序列。

标签: go terminal


【解决方案1】:

使用 github.com/creack/pty 库在 pty 中运行命令

这对我有用

转义序列在输出中可见

package main

import (
    "github.com/creack/pty"
    "io"
    "os"
    "os/exec"
)

func main() {
    hash := os.Args[1]
    cmd := exec.Command("git", "show", "--stat", hash)
    f, err := pty.Start(cmd)
    if err != nil {
        panic(err)
    }

    io.Copy(os.Stdout, f)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 2011-10-17
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多