get system cpu temperature in celsius in python

To get system CPU temperature in Celsius in Python, we can use the psutil library, which provides an interface for retrieving information on running processes and system utilization (including CPU temperature).

Here's the code to retrieve the CPU temperature in Celsius:

main.py
import psutil

temperature = psutil.sensors_temperatures().get('coretemp')[0].current
print(f"CPU Temperature: {temperature}°C")
129 chars
5 lines

We first import the psutil library. We then call the psutil.sensors_temperatures() method to retrieve a dictionary of temperature data (which includes the CPU temperature and temperature of other system components).

We then use the get() method to retrieve the temperature data for the coretemp sensor (which is where the CPU temperature is typically reported). We then access the current temperature value for this sensor (which is returned as a float).

Finally, we print the CPU temperature value in Celsius using an f-string.

gistlibby LogSnag