GO語言菜譜

分別捕獲exec.Command()標準輸出和錯誤輸出

參考:https://blog.kowalczyk.info/article/wOYk/advanced-command-execution-in-go-with-osexec.htmlhtml

func main() {
    cmd := exec.Command("ls", "-lah")
    var stdout, stderr bytes.Buffer
    cmd.Stdout = &stdout
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        log.Fatalf("cmd.Run() failed with %s\n", err)
    }
    outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
    fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)
}
相關文章
相關標籤/搜索