os/exec
使用演示
func Command(name string, arg ...string) *Cmdnamearg
func (c *Cmd) CombinedOutput() ([]byte, error)
CombinedOutput
可以调用Shell程序来执行Shell命令:
func (c *Cmd) Start() errorfunc (c *Cmd) Wait() error
Startfunc (c *Cmd) StderrPipe() (io.ReadCloser, error)func (c *Cmd) StdinPipe() (io.WriteCloser, error)func (c *Cmd) StdoutPipe() (io.ReadCloser, error)Wait
如果使用的是前面阻塞的方式的话,会等到命令结束后才会输出消息。
os/execStartCombinedOutput
func CommandContext(ctx context.Context, name string, arg ...string) *CmdctxCancel
Cmd结构体
type Cmd struct {Path string // 程序路径,如果使用相对路径,则会使用相对于下面Dir的路径Args []string // 程序执行参数Env []string // 程序运行环境变量,如果未指定则使用当前程序的环境变量Dir string // 程序执行的工作目录,如果未指定则使用当前程序的目录Stdin io.Reader // 标准输入,如果未指定的话就选择系统空设备,该参数也可以指定一个文件Stdout io.Writer // 标准输出,如果未指定的话就选择系统空设备,该参数也可以指定一个文件Stderr io.Writer // 标准错误输出,如果未指定的话就选择系统空设备,该参数也可以指定一个文件ExtraFiles []*os.File // 程序要打开的其它文档SysProcAttr *syscall.SysProcAttr // 可选的特定操作系统的属性Process *os.Process // 程序进程ProcessState *os.ProcessState // 程序进程状态Err error // Cancel func() error // WaitDelay time.Duration //
}
总结
Golang执行执行外部程序与Shell命令还是比较方便的,实际使用中更多的需要注意阻塞方法以及持续执行的外部程序的处理。