package exec用于运行外部命令,它封装了os.StartProcess,从而使操作更容易。
Index
- Variables
- func LookPath(file string) (string, error)
- type Cmd
- func Command(name string, arg ...string) *Cmd
- func (c *Cmd) CombinedOutput() ([]byte, error)
- func (c *Cmd) Output() ([]byte, error)
- func (c *Cmd) Run() error
- func (c *Cmd) Start() error
- func (c *Cmd) StderrPipe() (io.ReadCloser, error)
- func (c *Cmd) StdinPipe() (io.WriteCloser, error)
- func (c *Cmd) StdoutPipe() (io.ReadCloser, error)
- func (c *Cmd) Wait() error
- type Error
- type ExitError
Examples
Package Files
1. 基本函数
func LookPath
func LookPath(file string) (string, error)LookPath根据所给的二进制文件名file在PATH环境变量中寻找此二进制文件所在的路径信息:
path, err := exec.LookPath("fortune") if err != nil { log.Fatal("installing fortune is in your future") } fmt.Printf("fortune is available at %s\n", path)2. type Cmd
type Cmd struct { Path string Args []string Dir string Stdin io.Reader Stdout io.Writer Stderr io.Writer ExtraFiles []*os.File SysProcAttr *syscall.SysProcAttr Process *os.Process ProcessState *os.ProcessState }Cmd代表一个外部命令,此外部命令已准备好或已经在run。
func Command
func Command(name string, arg ...string) *CmdCommand返回用于执行name代表的命令的Cmd结构,Cmd中设置了Path和Args,其它fields都为空。例子如下:
cmd := exec.Command("tr", "a-z", "A-Z") cmd.Stdin = strings.NewReader("some input") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } fmt.Printf("in all caps: %q\n", out.String())
func (*Cmd) CombinedOutput
func (c *Cmd) CombinedOutput() ([]byte, error)运行命令c,并返回combined output和error。
func (*Cmd) Output
func (c *Cmd) Output() ([]byte, error)运行命令c,并返回标准输出,例子如下:
out, err := exec.Command("date").Output() if err != nil { log.Fatal(err) } fmt.Printf("The date is %s\n", out)
func (*Cmd) Run
func (c *Cmd) Run() errorRun运行指定的命令c,并等待其完成。
func (*Cmd) Start
func (c *Cmd) Start() errorStart也运行一个指定的命令c,但不等待其完成。例子如下:
cmd := exec.Command("sleep", "5") err := cmd.Start() if err != nil { log.Fatal(err) } log.Printf("Waiting for command to finish...") err = cmd.Wait() log.Printf("Command finished with error: %v", err)
func (*Cmd) Wait
func (c *Cmd) Wait() errorWait等待命令c退出,命令c必须是由Start方法运行的。会阻塞在那里?
有疑问加站长微信联系(非本文作者)