dougang1605 2019-02-01 09:15
浏览 101
已采纳

如何读取带有颜色属性的命令输出?

Is it possible to read a commands output with its color attributes. I mean, can we read the actual escape sequences.

for instance; A command output is red colored:

Hello

I want to read it as :

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

Currently I am reading it like:

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)
}
  • 写回答

1条回答 默认 最新

  • duan20145 2019-02-01 11:12
    关注

    Use the github.com/kr/pty library to run the command in a pty

    This works for me

    The escape sequences are visible in the output

    package main
    
    import (
        "github.com/kr/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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计