github.com/sandwich-go/boost@v1.3.29/xproc/stderr_as_err.go (about) 1 package xproc 2 3 import ( 4 "bytes" 5 "errors" 6 "strings" 7 ) 8 9 var DefaultManager = NewManager() 10 11 // Run 运行指定命令 12 // Note: 13 // 接管stdOut,stdErr,数据被缓存不会随执行输出 14 // 同时将stdError的内容看做错误以error返回 15 func Run(path string, opt ...ProcessOption) (string, error) { 16 cc := NewProcessOptions(opt...) 17 stdOut := new(bytes.Buffer) 18 stdErr := new(bytes.Buffer) 19 cc.Stdout = stdOut 20 cc.Stderr = stdErr 21 return run(NewProcessWithOptions(path, cc), stdOut, stdErr) 22 } 23 24 // ShellRun 启动shell运行指定命令 25 // Note: 26 // 接管stdOut,stdErr,数据被缓存不会随执行输出 27 // 同时将stdError的内容看做错误以error返回 28 func ShellRun(cmd string, opt ...ProcessOption) (string, error) { 29 cc := NewProcessOptions(opt...) 30 stdOut := new(bytes.Buffer) 31 stdErr := new(bytes.Buffer) 32 cc.Stdout = stdOut 33 cc.Stderr = stdErr 34 return run(NewProcessShellCmdWithOptions(cmd, cc), stdOut, stdErr) 35 } 36 37 func run(process *Process, stdOut, stdErr *bytes.Buffer) (string, error) { 38 err := process.Run() 39 if err != nil { 40 if stdErr.Len() > 0 { 41 return "", errors.New(strings.TrimSuffix(stdErr.String(), "\n")) 42 } 43 return "", err 44 } 45 return strings.TrimSuffix(stdOut.String(), "\n"), nil 46 }