13.6 启动外部命令和程序

Kesa...小于 1 分钟

13.6 启动外部命令和程序

使用下列方式可以启动外部程序:

  • os
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
  • os/exec包 创建命令

    func Command(name string, arg ...string) *Cmd
    

13_5_panic_recover_closure.go

package chapter_13

import (
   "fmt"
   "os"
   "os/exec"
   "strings"
)

func execCmd() {
   ls := exec.Command("ls")
   o, err := ls.CombinedOutput()
   check(err)
   fmt.Printf("Output:\n%s", string(o))

   fmt.Println(strings.Repeat("-", 20))
   env := os.Environ()
   procAttr := &os.ProcAttr{
      Env: env,
      Files: []*os.File{
         os.Stdin,
         os.Stdout,
         os.Stderr,
      },
   }
   _, err = os.StartProcess(`D:\GCC\bin\ls.exe`, []string{}, procAttr)
   check(err)
}

func check(err error) {
   if err != nil {
      panic(err)
   }
}
Output:
13_5_panic_recover_closure.go
13_5_panic_recover_closure_test.go
13_6_exec.go
13_6_exec_test.go
panic_recover.go
panic_recover_test.go
--------------------
13_5_panic_recover_closure.go
13_5_panic_recover_closure_test.go
13_6_exec.go
13_6_exec_test.go
panic_recover.go
panic_recover_test.go
上次编辑于:
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.2