1

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)
}
isacikgoz
  • 106
  • 1
  • 8
  • 2
    How are you reading command output? What have you tried? Show your code .What problems are you encountering? – Jonathan Hall Feb 01 '19 at 09:18
  • 2
    Note that many commands will try to cleverly detect whether they’re printing to a terminal, and only print colours then. So if you redirect their output somewhere else chances are there are no ANSI escape sequences there. – Biffen Feb 01 '19 at 09:31

1 Answers1

2

Use the github.com/creack/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/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)
}
nvidot
  • 1,262
  • 1
  • 7
  • 20
Vorsprung
  • 32,923
  • 5
  • 39
  • 63