Getting Python version using Go

巧了我就是萌 提交于 2021-01-27 04:57:07

问题


I'm trying to get my Python version using 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()
}

This returns empty slices:

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

Any idea what I'm doing wrong?


回答1:


$ python --version
Python 2.7.2
$ python --version 1>/dev/null # hide stdout
Python 2.7.2
$ python --version 2>/dev/null # hide stderr

We can conclude that the output goes to stderr. Now I took a look at Go's docs, and guess what, cmd.Output only captures stdout (docs). You should use cmd.CombinedOutput (docs) :

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



来源:https://stackoverflow.com/questions/20909598/getting-python-version-using-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!