Let's say I want to run 'ls' in a go program, and store the results in a string. There seems to be a few commands to fork processes in the exec and os packages, but they require file arguments for stdout, etc. Is there a way to get the output as a string?
+3
A:
Use exec.Run, passing Pipe for stdout. Read from the pipe that it returns.
Glomek
2009-12-09 21:44:37
That should probably be referred to as exec.Run() (which returns a Cmd), rather than Cmd.Run.
esm
2009-12-10 04:25:53
Whoops. Thanks.
Glomek
2009-12-10 05:14:48
+3
A:
Use exec.Run by specifying Pipe as the stdout (and stderr if you want). It will return cmd, which contains an os.File in the Stdout (and Stderr) fields. Then you can read it using for example ioutil.ReadAll.
Example:
package main
import (
"exec";
"io/ioutil";
)
func main() {
if cmd, e := exec.Run("/bin/ls", nil, nil, exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil {
b, _ := ioutil.ReadAll(cmd.Stdout)
println("output: " + string(b))
}
}
yuku
2009-12-11 06:13:12