Go lang convert os.File output to String-ThrowExceptions

Exception or error:

How to convert Os.File output into string instead of printing to shell.
I am using github.com/kr/pty library to execute commands.

How can convert the output to sting instead of printing to console.

f belongs to Os.File in below example. How to convert it to string.

package main

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

func run_command(cmd string){
    c := exec.Command("/bin/sh", "-c", cmd)
    f, err := pty.Start(c)
    if err != nil {
        panic(err)
    }
    io.Copy(os.Stdout, f)
}

func main() {
    run_command("ls -lrt");
}
How to solve:

An *os.File is an io.Reader. There are a few ways to convert the contents of an io.Reader to a string using the standard library.

The strings.Builder approach might perform better than the other approaches because strings.Builder does not allocate memory when converting the accumulated bytes to a string. This performance benefit is probably negligible in the context of the question.

Otherwise, the choice of approach is a matter of taste and opinion.

strings.Builder

var buf strings.Builder
_, err := io.Copy(&buf, f)
if err != nil {
    // handle error
}
s := buf.String()

bytes.Buffer

var buf bytes.Buffer
_, err := buf.ReadFrom(f)
if err != nil {
    // handle error
}
s := buf.String()

ioutil.ReadAll

p, err := ioutil.Read(f)
if err != nil {
     // handle error
}
s := string(p)

Answer´╝Ü

Instead of

io.Copy(os.Stdout, f)

you can do

var buf bytes.Buffer
io.Copy(&buf, f)
asString := string(buf.Bytes())

Leave a Reply

Your email address will not be published. Required fields are marked *