使用G获取Python版本

2024-09-29 01:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Go:

import (
    "log"
    "os/exec"
    "strings"
)

func verifyPythonVersion() {
    _, err := exec.LookPath("python")
    if err != nil {
        log.Fatalf("No python version located")

    }
    out, err := exec.Command("python", "--version").Output()
    log.Print(out)
    if err != nil {
        log.Fatalf("Error checking Python version with the 'python' command: %v", err)
    }
    fields := strings.Fields(string(out))
    log.Print(fields)

}

func main() {
    verifyPythonVersion()
}

这将返回空切片:

2014/01/03 20:39:53 []
2014/01/03 20:39:53 []

知道我做错了什么吗?你知道吗


Tags: importloggofieldsifversionoutexec
1条回答
网友
1楼 · 发布于 2024-09-29 01:31:49
$ python  version
Python 2.7.2
$ python  version 1>/dev/null # hide stdout
Python 2.7.2
$ python  version 2>/dev/null # hide stderr

我们可以得出结论,输出到stderr。现在我看了一下Go的文档,猜猜看,cmd.Output只捕获stdout(docs)。您应该使用cmd.CombinedOutputdocs):

CombinedOutput runs the command and returns its combined standard output and standard error.

相关问题 更多 >