Executing commands
The os/exec
package has functions to run externalcommands, and is the premier way to execute commands from within a Go program.It works by defining a *exec.Cmd
structure for which it defines a number ofmethods. Let’s execute ls -l
:
import "os/exec"
cmd := exec.Command("/bin/ls", "-l")
err := cmd.Run()
The above example just runs “ls -l” without doing anything with the returneddata, capturing the standard output from a command is done as follows:
cmd := exec.Command("/bin/ls", "-l")
buf, err := cmd.Output()
And buf
is byte slice, that you can further use in your program.
当前内容版权归 Miek Gieben 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Miek Gieben .