我在使用Ubuntu14.04并在命令行上执行diff时遇到了问题。查看下面的Go代码:
package main
import "fmt"
import "log"
import "os/exec"
func main() {
output, err := exec.Command("diff", "-u", "/tmp/revision-1", "/tmp/revision-4").Output()
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(output))
}如果使用go run test.go执行此操作,将得到以下错误:
2015/03/18 14:39:25 exit status 1
exit status 1因此,diff出了问题,它将1作为其退出代码返回。似乎只有diff命令会引发错误。如果我使用cat或wc命令,则代码运行良好。
知道为什么diff在这里不工作,但其他命令可以吗?
发布于 2015-03-18 15:16:42
使用exec运行程序时,如果退出代码不是0,则会出现错误。从医生那里:
如果命令运行,则返回的错误为零,在复制stdin、stdout和stderr时没有问题,并且退出状态为零。 如果命令无法运行或未成功完成,则错误类型为*ExitError。对于I/O问题,可能会返回其他错误类型。
因此,这里发生的情况是,diff在文件不同时返回一个错误,但是您将它视为运行时错误。只需更改您的代码,以反映它不是。这是可能的,通过检查错误。
例如,类似这样的事情:
output, err := exec.Command("diff", "-u", "/tmp/revision-1", "/tmp/revision-4").CombinedOutput()
if err != nil {
switch err.(type) {
case *exec.ExitError:
// this is just an exit code error, no worries
// do nothing
default: //couldnt run diff
log.Fatal(err)
}
}另外,我已经更改了get CombinedOutput,所以如果发生任何差异特定的错误,您也会看到stderr。
注意到,即使其中一个文件不存在,您也会得到一个“有效”错误。因此,您可以通过这样的操作来检查ExitError的退出代码:
switch e := err.(type) {
case *exec.ExitError:
// we can check the actual error code. This is not platform portable
if status, ok := e.Sys().(syscall.WaitStatus); ok {
// exit code 1 means theres a difference and is not an error
if status.ExitStatus() != 1 {
log.Fatal(err)
}
}https://stackoverflow.com/questions/29125248
复制相似问题