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");
}
Instead of
io.Copy(os.Stdout, f)
you can do
var buf bytes.Buffer
io.Copy(&buf, f)
asString := buf.String()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With