這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
有一個需求是用go語言程式調用外部命令時,允許使用管道符,如 ls | wc -l
Go語言對外部命令的調用進行了一定的封裝,下面來試一下:
package mainimport ("os""os/exec")func main() {run1()}func run1() {cmd := exec.Command("ls", "|", "wc", "-l")cmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrcmd.Start()cmd.Run()cmd.Wait()}
這樣執行時,控制台會打出錯誤:
ls: 無法訪問|: 沒有那個檔案或目錄
ls: 無法訪問wc: 沒有那個檔案或目錄
難道Go程式不能使用管道符命令嗎?帶這此問題,我查了大量的資料,終於發現應該這樣寫(run2):
package mainimport ("os""os/exec")func main() {// run1()run2()}func run1() {cmd := exec.Command("ls", "|", "wc", "-l")cmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrcmd.Start()cmd.Run()cmd.Wait()}func run2() {c1 := exec.Command("ls")c2 := exec.Command("wc", "-l")c2.Stdin, _ = c1.StdoutPipe()c2.Stdout = os.Stdoutc2.Stderr = os.Stderrc2.Start()c1.Run()c2.Wait()}
哈哈,這樣就沒問題啦。
下面,我們來點進階的,如查詢 nginx 主進行的PID號:
ps -eaf|grep "nginx: master"|grep -v "grep"|awk '{print $2}'(見 run3)
package mainimport ("os""os/exec")func main() {// run1()// run2()run3()}func run1() {cmd := exec.Command("ls", "|", "wc", "-l")cmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrcmd.Start()cmd.Run()cmd.Wait()}func run2() {c1 := exec.Command("ls")c2 := exec.Command("wc", "-l")c2.Stdin, _ = c1.StdoutPipe()c2.Stdout = os.Stdoutc2.Stderr = os.Stderrc2.Start()c1.Run()c2.Wait()}func run3() {c1 := exec.Command("ps", "-eaf")c2 := exec.Command("grep", `"nginx: master"`)c3 := exec.Command("grep", "-v", `"grep"`)c4 := exec.Command("awk", `'{print $2}'`)c2.Stdin, _ = c1.StdoutPipe()c3.Stdin, _ = c2.StdoutPipe()c4.Stdin, _ = c3.StdoutPipe()c4.Stdout = os.Stdoutc4.Stderr = os.Stderrc4.Start()c3.Start()c2.Start()c1.Run()c4.Wait()}
靠,又不行了,提示:
awk: 1: unexpected character '''
awk: 1: unexpected character '''
它不能支援參數中有引號的內容!
怎麼辦,難道真的沒轍了嗎?老天不負有心人,終於被我找到解決辦法了,而且更簡單:
package mainimport ("os""os/exec")func main() {// run1()// run2()// run3()run4()}func run1() {cmd := exec.Command("ls", "|", "wc", "-l")cmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrcmd.Start()cmd.Run()cmd.Wait()}func run2() {c1 := exec.Command("ls")c2 := exec.Command("wc", "-l")c2.Stdin, _ = c1.StdoutPipe()c2.Stdout = os.Stdoutc2.Stderr = os.Stderrc2.Start()c1.Run()c2.Wait()}func run3() {c1 := exec.Command("ps", "-eaf")c2 := exec.Command("grep", `"nginx: master"`)c3 := exec.Command("grep", "-v", `"grep"`)c4 := exec.Command("awk", `'{print $2}'`)c2.Stdin, _ = c1.StdoutPipe()c3.Stdin, _ = c2.StdoutPipe()c4.Stdin, _ = c3.StdoutPipe()c4.Stdout = os.Stdoutc4.Stderr = os.Stderrc4.Start()c3.Start()c2.Start()c1.Run()c4.Wait()}func run4() {cmd := exec.Command("/bin/sh", "-c", `ps -eaf|grep "nginx: master"|grep -v "grep"|awk '{print $2}'`)cmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrcmd.Start()cmd.Run()cmd.Wait()}