tags:

views:

138

answers:

3

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
That should probably be referred to as exec.Run() (which returns a Cmd), rather than Cmd.Run.
esm
Whoops. Thanks.
Glomek
+1  A: 

Two options, depending on the paradigm you prefer:

  1. os.ForkExec()
  2. exec.Run()
esm
+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