<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
CombinedOutput()
執行程式返回 standard output and standard error
func main() { cmd := exec.Command("ls", "-lah") out, err := cmd.CombinedOutput() if err != nil { log.Fatalf("cmd.Run() failed with %sn", err) } fmt.Printf("combined out:n%sn", string(out)) }
Output()
執行程式返回standard output
func main() { out, err := exec.Command("date").Output() if err != nil { log.Fatal(err) } fmt.Printf("The date is %sn", out) }
用buffer接受輸出
func main() { cmd := exec.Command("ls", "-lah") var stdin, stdout, stderr bytes.Buffer cmd.Stdin = &stdin cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { log.Fatalf("cmd.Run() failed with %sn", err) } outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes()) fmt.Printf("out:n%snerr:n%sn", outStr, errStr) }
直接列印到螢幕
func main() { cmd := exec.Command("ls", "-lah") cmd.Stdout = os.Stdout cmd.Stderr = os.Stdout err := cmd.Run() if err != nil { log.Fatalf("cmd.Run() failed with %sn", err) } }
cmd.Run() 阻塞等待命令執行結束
cmd.Start() 不會等待命令完成
package main import ( "bytes" "fmt" "io" "log" "os" "os/exec" ) func main() { var stdoutBuf, stderrBuf bytes.Buffer cmd := exec.Command("bash", "-c", "for i in 1 2 3 4;do echo $i;sleep 2;done") stdoutIn, _ := cmd.StdoutPipe() stderrIn, _ := cmd.StderrPipe() var errStdout, errStderr error stdout := io.MultiWriter(os.Stdout, &stdoutBuf) stderr := io.MultiWriter(os.Stderr, &stderrBuf) err := cmd.Start() if err != nil { log.Fatalf("cmd.Start() failed with '%s'n", err) } go func() { _, errStdout = io.Copy(stdout, stdoutIn) }() go func() { _, errStderr = io.Copy(stderr, stderrIn) }() err = cmd.Wait() if err != nil { log.Fatalf("cmd.Run() failed with %sn", err) } if errStdout != nil || errStderr != nil { log.Fatal("failed to capture stdout or stderrn") } outStr, errStr := string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()) fmt.Printf("nout:n%snerr:n%sn", outStr, errStr) }
func main() { cmd := exec.Command("bash", "-c", "programToExecute") additionalEnv := "programToExecute=ls" newEnv := append(os.Environ(), additionalEnv) cmd.Env = newEnv out, err := cmd.CombinedOutput() if err != nil { log.Fatalf("cmd.Run() failed with %sn", err) } fmt.Printf("%s", out) }
func checkLsExists() { path, err := exec.LookPath("ls") if err != nil { fmt.Printf("didn't find 'ls' executablen") } else { fmt.Printf("'ls' executable is in '%s'n", path) } }
func main() { c1 := exec.Command("ls") c2 := exec.Command("wc", "-l") r, w := io.Pipe() c1.Stdout = w c2.Stdin = r var b2 bytes.Buffer c2.Stdout = &b2 c1.Start() c2.Start() c1.Wait() w.Close() c2.Wait() io.Copy(os.Stdout, &b2) }
或者
func main() { c1 := exec.Command("ls") c2 := exec.Command("wc", "-l") c2.Stdin, _ = c1.StdoutPipe() c2.Stdout = os.Stdout _ = c2.Start() _ = c1.Run() _ = c2.Wait() }
反正下面這樣是不行的
func main() { c := exec.Command("ls", "|", "wc", "-l") c.Stdout = os.Stdout _ = c.Run() }
不嫌醜可以用bash -c
func main() { cmd := "cat /proc/cpuinfo | egrep '^model name' | uniq | awk '{print substr($0, index($0,$4))}'" out, err := exec.Command("bash", "-c", cmd).Output() if err != nil { fmt.Printf("Failed to execute command: %s", cmd) } fmt.Println(string(out)) }
func main() { cmd := exec.Command("ls", "-la") stdout, _ := cmd.StdoutPipe() cmd.Start() reader := bufio.NewReader(stdout) for { line, err := reader.ReadString('n') line = strings.TrimSpace(line) if err != nil || io.EOF == err { break } log.Println(line) } cmd.Wait() }
func RunCommand(name string, args ...string) (stdout string, stderr string, exitCode int) { log.Println("run command:", name, args) var outbuf, errbuf bytes.Buffer cmd := exec.Command(name, args...) cmd.Stdout = &outbuf cmd.Stderr = &errbuf err := cmd.Run() stdout = outbuf.String() stderr = errbuf.String() if err != nil { // try to get the exit code if exitError, ok := err.(*exec.ExitError); ok { ws := exitError.Sys().(syscall.WaitStatus) exitCode = ws.ExitStatus() } else { // This will happen (in OSX) if `name` is not available in $PATH, // in this situation, exit code could not be get, and stderr will be // empty string very likely, so we use the default fail code, and format err // to string and set to stderr log.Printf("Could not get exit code for failed program: %v, %v", name, args) exitCode = defaultFailedCode if stderr == "" { stderr = err.Error() } } } else { // success, exitCode should be 0 if go is ok ws := cmd.ProcessState.Sys().(syscall.WaitStatus) exitCode = ws.ExitStatus() } log.Printf("command result, stdout: %v, stderr: %v, exitCode: %v", stdout, stderr, exitCode) return }
參考連結:
https://saucer-man.com/backend_development/571.html
到此這篇關於詳解golang執行Linux shell命令完整場景下的使用方法的文章就介紹到這了,更多相關golang執行Linux shell內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45