Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Python version using Go

Tags:

python

go

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?

like image 212
jwesonga Avatar asked Jan 03 '14 17:01

jwesonga


People also ask

How do I check Python version?

If you have Python installed then the easiest way you can check the version number is by typing "python" in your command prompt. It will show you the version number and if it is running on 32 bit or 64 bit and some other information. For some applications you would want to have a latest version and sometimes not.

How do you check if I have Python installed?

Python is probably already installed on your system. To check if it's installed, go to Applications>Utilities and click on Terminal. (You can also press command-spacebar, type terminal, and then press Enter.) If you have Python 3.4 or later, it's fine to start out by using the installed version.


1 Answers

$ 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.

like image 154
ThinkChaos Avatar answered Sep 21 '22 13:09

ThinkChaos