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命令还是比较方便的,实际使用中更多的需要注意阻塞方法以及持续执行的外部程序的处理。
可以借助 github.com/creack/pty 来实现虚拟终端交互功能。