使用Go获取Python版本 [英] Getting Python version using Go

查看:69
本文介绍了使用Go获取Python版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Go获取我的Python版本:

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()
}

这将返回空片:

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

知道我在做什么错吗?

推荐答案

$ 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(文档):

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运行命令并返回其组合的标准输出和标准错误.

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

这篇关于使用Go获取Python版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆