我在用包s/exec http://golang.org/pkg/os/exec/在操作系统中执行命令,但我似乎没有找到获取退出代码的方法。虽然我可以读取输出 % f$ A5 b' n; ?: r7 LIE。 d' P+ V% D, \[code]package mainimport( "os/exec" "bytes" "fmt" "log" )func main() cmd := exec.Command("somecommand","parameter") var out bytes.Buffer cmd.Stdout = &out if err := cmd.Run() ; err != nil { //log.Fatal( cmd.ProcessState.Success())) log.Fatal( err fmt.Printf("%q\n",out.String()code] 5 p! ]# u' @) L; |解决方案: 7 @2 s" U& }9 p/ h 很容易确定退出代码是 0 还是其他。第一种情况下,cmd.Wait()返回 nil(除非设置管道时出现另一个错误)。 7 }2 Y w& j0 f+ D6 |; F8 S9 z/ W O+ u不幸的是,在错误的情况下,没有独立的平台方法可以获得退出代码。API 的部分原因。以下代码段适用于 Linux,但是我还没有在其他平台上测试过: 6 l% F2 W9 x' [0 Y6 t[code]package mainimport "os/exec"import "log"import "syscall"func main() cmd := exec.Command("git","blub") if err := cmd.Start(); err != nil log.Fatalf("cmd.Start: %v",err) } if err := cmd.Wait(); err != nil if exiterr,ok := err.(*exec.ExitError); ok // The program has exited with an exit code != This works on both Unix and Windows. Although package syscall is generally platform dependent,WaitStatus is defined for both Unix and Windows and in both cases has an ExitStatus() method with the same signature. if status,ok := exiterr.Sys().(syscall.WaitStatus); ok log.Printf("Exit Status: %d",status.ExitStatus()) else log.Fatalf("cmd.Wait: %v",err) code]