There is a convenience method on the result of exec.Command(), you can
read about it here
Cheers
Dave
package systemimport "exec"import "os"import "io/ioutil"import "strings"func Exec(bin string, arg string) (retStr string,err os.Error) {cmd,err:=exec.LookPath(bin)if err != nil {return "",err}if arg != "" {arg= cmd + " " + arg}a:=strings.Split(arg," ",-1)c,err := exec.Run(cmd, a,nil, "", exec.DevNull, exec.Pipe, exec.DevNull)if err != nil {return "",err}defer c.Close()out,_:=ioutil.ReadAll(c.Stdout)retStr= strings.TrimRight(string(out),"\n")return retStr,nil}
# Copyright 2009 The Go Authors. All rights reserved.# Use of this source code is governed by a BSD-style# license that can be found in the LICENSE file.include ../../Make.incTARG=systemGOFILES=\system.go\GOFILES+=$(GOFILES_$(GOOS))include ../../Make.pkg
package mainimport (
"system"
"fmt"
)func main() {
a,err:=system.Exec("uname","-a")
if err != nil {
fmt.Printf("Error: %v\n",err)
} else {
fmt.Printf("Uname returned: %s\n",a)
}
}
On Sunday, June 5, 2011, Kyle Lemons <kev...@google.com> wrote:
> No guarantees about removing trailing newlines or anything, but eliminating this sort of wrapper is exactly why Run was written. Your main could be written as:
> package main
>
>
> import ( "exec"
>
> "os" "log"
>
> )
> func main() {
>
> out, err := exec.Command("uname", "-a").Output()
>
> if err != nil { log.Fatalf("Error: %s", err)
>
> } os.Stdout.Write(out)
>
> }
> Cheers,
> On Sun, Jun 5, 2011 at 9:59 AM, Rich <rma...@gmail.com> wrote:
> What I did was create my own package that I called 'system'. I plan to add other functions into it as I need them but this simplifies the running of a command.
>
>
> System.go:package system
>
> import "exec"
>
> import "os"import "io/ioutil"import "strings"
> func Exec(bin string, arg string) (retStr string,err os.Error) {
>
> cmd,err:=exec.LookPath(bin) if err != nil { return "",err } if arg != "" {
>
> arg= cmd + " " + arg } a:=strings.Split(arg," ",-1) c,err := exec.Run(cmd, a,nil, "", exec.DevNull, exec.Pipe, exec.DevNull)
>
> if err != nil { return "",err } defer c.Close() out,_:=ioutil.ReadAll(c.Stdout)
>
> retStr= strings.TrimRight(string(out),"\n") return retStr,nil}
> I created a directory in $GOROOT/src/pkg/system, then copied / modified one of the make files from go:
>
>
> # Copyright 2009 The Go Authors. All rights reserved.# Use of this source code is governed by a BSD-style
Kyle -- I like your solution, but my system doesn't have an exec.Command:exec.go:9: undefined: exec.Command
Is this a new addition to one of the weekly builds? I also don't see it in the documentation: