5

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");
}
2
  • 2
    kr/pty writes to the terminal, that's actually the whole point of it. If you just want the program's stdout, you should use os/exec directly. It even has an example to show you how, you just need to string(out) on the resulting []byte. Commented Feb 3, 2018 at 10:35
  • 1
    If you really want to re-read the file (assuming it's an actual file, but I believe kr/pty writes to the console, so there's nothing to read back), you can always use ioutil.ReadAll on the *os.File. But again: the file pty opens is a terminal file descriptor, it just displays the contents, you don't be able to read them back. Commented Feb 3, 2018 at 10:43

2 Answers 2

4

Instead of

io.Copy(os.Stdout, f)

you can do

var buf bytes.Buffer
io.Copy(&buf, f)
asString := buf.String()
Sign up to request clarification or add additional context in comments.

Comments

2

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.ReadAll(f)
if err != nil {
     // handle error
}
s := string(p)

1 Comment

Does ioutil.Read need to be ioutil.ReadAll?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.