13.6 启动外部命令和程序
...小于 1 分钟
13.6 启动外部命令和程序
使用下列方式可以启动外部程序:
os
包
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
os/exec
包 创建命令func Command(name string, arg ...string) *Cmd
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