get system cpu temperature in fahrenheit in go

Here is an example program in Go to get the system CPU temperature in Fahrenheit:

main.go
package main

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

func main() {
    // Execute the command to get the temperature, assuming the "sensors" command is available
    out, err := exec.Command("sensors").Output()
    if err != nil {
        panic(err)
    }

    // Look for the line in the output containing the CPU temperature
    var temperatureStr string
    for _, line := range strings.Split(string(out), "\n") {
        if strings.Contains(line, "Core 0:") {
            temperatureStr = strings.TrimSpace(strings.Split(line, ":")[1])
            break
        }
    }

    // Parse the temperature (in Celsius) and convert to Fahrenheit
    temperatureCelsius, err := strconv.ParseFloat(strings.Trim(temperatureStr, "°C"), 64)
    if err != nil {
        panic(err)
    }
    temperatureFahrenheit := temperatureCelsius*1.8 + 32

    // Print the temperature in Fahrenheit
    fmt.Printf("CPU temperature: %.1f°F\n", temperatureFahrenheit)
}
973 chars
36 lines

This code uses the exec package to run the sensors command, which is commonly available on Linux systems to get hardware temperature readings. It then looks for the line in the output containing the CPU temperature, parses the temperature in Celsius, and converts it to Fahrenheit using the conversion formula. Finally, it prints the temperature in Fahrenheit to the console.

gistlibby LogSnag