get system cpu temperature in celsius in go

To get the system CPU temperature in Celsius in Go, you can use the os/exec package to run the command sensors (assuming that this command is available on your system). Then, you can parse the output of the command to extract the CPU temperature.

Here's how you can do it:

main.go
package main

import (
    "fmt"
    "os"
    "os/exec"
    "regexp"
    "strconv"
)

func main() {
    // Run the "sensors" command
    cmd := exec.Command("sensors")
    output, err := cmd.Output()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(1)
    }

    // Extract the CPU temperature from the output
    re := regexp.MustCompile(`^Core\s\d+:\s+\+(.*?)°C`)
    matches := re.FindAllStringSubmatch(string(output), -1)
    if len(matches) == 0 {
        fmt.Println("Error: could not find CPU temperature in output")
        os.Exit(1)
    }
    tempStr := matches[0][1]

    // Convert the temperature to a float64 value in Celsius
    temp, err := strconv.ParseFloat(tempStr, 64)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(1)
    }

    // Print the temperature in Celsius
    fmt.Printf("CPU temperature: %.1f°C\n", temp)
}
884 chars
39 lines

Note that this code extracts the temperature of the first CPU core. You can modify the regular expression to extract the temperature of a different core if needed. Also, keep in mind that the output format of the sensors command may vary depending on your system.

gistlibby LogSnag