利用Golang如何调用Linux命令详解

æ¬æä»ç»çæ¯Golangä½¿ç¨ os/exec æ¥æ§è¡ Linux å½ä»¤ï¼å享åºæ¥ä¾å¤§å®¶åè学习ï¼ä¸é¢æ¥çç详ç»çä»ç»ï¼

ä¸é¢æ¯ä¸ä¸ªç®åç示ä¾ï¼

package main
 
 import (
  "fmt"
  "io/ioutil"
  "os/exec"
 )
 
 func main() {
  cmd := exec.Command("/bin/bash", "-c", `df -lh`)
 
  //å建è·åå½ä»¤è¾åºç®¡é
  stdout, err := cmd.StdoutPipe()
  if err != nil {
   fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err)
   return
  }
 
  //æ§è¡å½ä»¤
  if err := cmd.Start(); err != nil {
   fmt.Println("Error:The command is err,", err)
   return
  }
 
  //读åææè¾åº
  bytes, err := ioutil.ReadAll(stdout)
  if err != nil {
   fmt.Println("ReadAll Stdout:", err.Error())
   return
  }
 
  if err := cmd.Wait(); err != nil {
   fmt.Println("wait:", err.Error())
   return
  }
  fmt.Printf("stdout:\n\n %s", bytes)
 }

æèå建ä¸ä¸ªç¼å²è¯»åå¨æè¡è¯»åï¼

package main
 
 import (
  "bufio"
  "fmt"
  "os/exec"
 )
 
 func main() {
  cmd := exec.Command("/bin/bash", "-c", `df -lh`)
 
  //å建è·åå½ä»¤è¾åºç®¡é
  stdout, err := cmd.StdoutPipe()
  if err != nil {
   fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err)
   return
  }
 
  //æ§è¡å½ä»¤
  if err := cmd.Start(); err != nil {
   fmt.Println("Error:The command is err,", err)
   return
  }
 
  //使ç¨å¸¦ç¼å²ç读åå¨
  outputBuf := bufio.NewReader(stdout)
 
  for {
 
   //ä¸æ¬¡è·åä¸è¡,_ è·åå½åè¡æ¯å¦è¢«è¯»å®
   output, _, err := outputBuf.ReadLine()
   if err != nil {
 
    // å¤æ­æ¯å¦å°æ件çç»å°¾äºå¦ååºé
    if err.Error() != "EOF" {
     fmt.Printf("Error :%s\n", err)
    }
    return
   }
   fmt.Printf("%s\n", string(output))
  }
 
  //wait æ¹æ³ä¼ä¸ç´é»å¡å°å¶æå±çå½ä»¤å®å¨è¿è¡ç»æ为止
  if err := cmd.Wait(); err != nil {
   fmt.Println("wait:", err.Error())
   return
  }
 }

è¾åºç»æï¼

利用Golang如何调用Linux命令详解

å¨åè¿å¥ if err.Error() != "EOF" æ¶ï¼ä¸ç´ä»¥ä¸ºå¯ä»¥ç´æ¥å° error ç±»åç´æ¥è½¬ä¸º string ç¶åå°±å¯ä»¥æ¯è¾äºï¼æ以åå¼å§åç代ç æ¯è¿æ ·ç if string(err) != "EOF" ,ä½æ¯ä¸ç´æ¥ä¸é¢è¿ä¸ªé误ï¼

# command-line-arguments
 ./exec_command.go:36: cannot convert err (type error) to type string

äºæ¯æ¥äºä¸ææç½ï¼error ç±»åæ¬èº«æ¯ä¸ä¸ªé¢å®ä¹å¥½çæ¥å£ï¼éé¢å®ä¹äºä¸ä¸ªmethodï¼

type error interface {
  Error() string
 }

æ以 err.Error() ææ¯ä¸ä¸ª string ç±»åçè¿åå¼ã

æ»ç»

以ä¸å°±æ¯è¿ç¯æç« çå¨é¨å容äºï¼å¸ææ¬æçå容对大家ç学习æèå·¥ä½è½å¸¦æ¥ä¸å®ç帮å©ï¼å¦ææçé®å¤§å®¶å¯ä»¥çè¨äº¤æµï¼è°¢è°¢å¤§å®¶å¯¹èæ¬ä¹å®¶çæ¯æã

相关推荐