Check the temperature of your CPU using Python (and other cool tricks)

As developers, it‘s important for us to keep tabs on our system resources. Monitoring things like CPU usage, memory consumption, disk space, and network I/O allows us to optimize performance, diagnose issues, and prevent problems before they arise. Luckily, Python makes it easy to do this using the excellent psutil module.

In this article, I‘ll show you how to harness the power of psutil to monitor your system resources from Python scripts or applications. We‘ll focus on one common use case – checking your CPU temperature to make sure your processor isn‘t overheating. Then we‘ll explore some other nifty things you can do with psutil to keep an eye on every aspect of your system. Let‘s dive in!

Getting started with psutil

First things first – you‘ll need to install psutil if you don‘t have it already. You can install it using pip:

pip install psutil 

Once installed, you can import it into your Python scripts or an interactive shell like IPython. Let‘s launch IPython and give it a shot:

In [1]: import psutil

In [2]: psutil.cpu_percent()
Out[2]: 7.5

In [3]: psutil.virtual_memory()
Out[3]: svmem(total=16624865280, available=7382515712, percent=55.6, used=8252456960, free=8372408320)

As you can see, with just a few lines of code we can retrieve the current CPU usage percentage and a snapshot of the system memory usage. The psutil module provides a simple interface for fetching all kinds of system information.

Checking CPU temperature

One important aspect of CPU health is the temperature. If your CPU gets too hot, it can lead to stability issues, reduced performance, and even permanent damage. Keeping an eye on the CPU temp allows you to identify cooling problems before they get out of hand.

With psutil, checking your CPU temperature is a breeze:

import psutil

temp_info = psutil.sensors_temperatures()

if not temp_info:
    print("No temperature sensors found")
else:
    for name, entries in temp_info.items(): 
        print(f"Sensor ‘{name}‘:")
        for entry in entries:
            print(f" - {entry.label or name}: {entry.current}°C (high={entry.high}°C, critical={entry.critical}°C)")

This code snippet retrieves temperature info from all available sensors using psutil.sensors_temperatures(). It returns a dictionary mapping sensor names to a list of temperature entries. Each entry contains the current, high, and critical temperature thresholds in Celsius.

On my Windows laptop, the output looks something like this:

Sensor ‘coretemp‘:
 - Core 0: 40.0°C (high=100.0°C, critical=100.0°C)  
 - Core 1: 38.0°C (high=100.0°C, critical=100.0°C)
Sensor ‘acpitz‘:
 - acpitz: 16.8°C (high=18.8°C, critical=18.8°C)

This shows I have two temperature sensors – one for the CPU cores and one for the ACPI thermal zone. The CPU cores are currently running at a reasonable 38-40°C, well below the high and critical thresholds of 100°C. The ACPI sensor is reporting an ambient temperature of about 17°C.

So what temperature is "normal" for a CPU? It depends on the specific processor, but in general, anything up to 70°C is considered safe. Above that, you may start experiencing thermal throttling, which reduces performance to prevent damage. Temperatures above 90°C are getting into the danger zone and may cause system instability or crashes.

By monitoring your CPU temperature periodically, you can spot cooling issues before they lead to a meltdown. For example, if you notice the temperature consistently creeping up over time, it may indicate a buildup of dust in your computer‘s fans or heatsinks impairing heat dissipation. Or if the temperature spikes under heavy CPU load, you may need to improve airflow in your computer case or invest in a better CPU cooler.

Other neat tricks with psutil

Checking CPU temps is handy, but it‘s just the tip of the iceberg of what you can do with psutil. Let‘s take a quick tour of some other useful features for keeping tabs on your system:

CPU

  • Get CPU usage percentage per CPU and overall:
psutil.cpu_percent(percpu=True)
psutil.cpu_percent()
  • Get system CPU times (user, system, idle, etc):
psutil.cpu_times()
  • Get CPU statistics:
psutil.cpu_stats()  
  • Get CPU frequency info:
psutil.cpu_freq()

Memory

  • Get memory usage stats:
psutil.virtual_memory()
  • Get swap memory info:
psutil.swap_memory()

Disks

  • Get disk usage for a certain path:
psutil.disk_usage(‘/‘)
  • Get disk I/O statistics:
psutil.disk_io_counters()
  • Get all mounted disk partitions:
psutil.disk_partitions() 

Network

  • Get network I/O stats:
psutil.net_io_counters()
  • Get network interfaces and their stats:
psutil.net_if_addrs() 
psutil.net_if_stats()
  • Get socket connections:
psutil.net_connections()

Sensors

  • Get battery status:
psutil.sensors_battery()
  • Get fan speeds:
psutil.sensors_fans()

Other

  • Get boot time:
psutil.boot_time()
  • Get all logged in users:
psutil.users()

As you can see, psutil provides an extensive set of functions for retrieving detailed information about virtually every aspect of your system. Definitely take some time to peruse the documentation and experiment with these in the Python REPL to get a feel for the data they provide.

Practical applications

Alright, so psutil gives us access to a wealth of system info. But what can we actually do with it?

Here are a few ideas for projects you could build leveraging psutil:

  1. A system resource dashboard – Create a web app using a framework like Flask or Django that displays real-time graphs and stats for CPU usage, memory usage, disk usage, network traffic, temperatures, etc. You could even include some controls to launch/kill processes or set alert thresholds.

  2. Automated email/SMS alerts – Write a Python script that periodically checks system resource usage and sends an email or SMS notification if anything exceeds a defined threshold. For instance, you could alert if CPU usage is over 90% for more than 5 minutes or if free disk space drops below 10%.

  3. Correlate CPU usage to temperature – Use psutil to log CPU usage and temperature to a file or database at regular intervals. Then analyze the data to understand how CPU load affects temperature for your system. You could generate some nice graphs with Matplotlib and use linear regression to derive a formula relating usage to temperature.

  4. Investigate a performance issue – Say a user reports that your Python application is consuming excessive memory or CPU. You can use psutil to introspect the program live, examining its memory usage, CPU consumption, open files, subprocesses, threads, and so on. Visualize the data to detect memory leaks, identify CPU bottlenecks, and pinpoint the root cause.

The possibilities are endless! Any time you need to access or manipulate system resources from Python, psutil is a worthy addition to your toolkit. It can help you bolster the reliability and performance of your applications.

Alternatives to psutil

While psutil is arguably the most popular and full-featured Python library for accessing system resources, there are some alternatives worth mentioning:

  • platform module – This is part of the Python standard library and provides some basic system info like OS name, Python version, processor name, etc. However, it‘s quite limited compared to psutil.

  • resource module – Also part of the standard library, this module allows retrieval of resource usage info (CPU time, max memory, etc) for the current process. It‘s less extensive than psutil in terms of the types of resources tracked.

  • wmi module – For Windows only, this 3rd party module allows querying Windows Management Instrumentation (WMI) data. You can retrieve detailed system info, but the interface is a bit clunky compared to psutil.

  • Command line tools – Most OSes ship with built-in utilities like ps, top, df, free, etc. that can retrieve system stats. You can invoke these from Python using the subprocess module and parse their output. This works but is less convenient than using a dedicated library.

Personally, I reach for psutil most of the time. It strikes a good balance between ease of use, cross-platform support, and breadth of features. Plus the documentation is excellent which makes it very approachable.

Conclusion

If you made it this far, you should have a solid handle on how to leverage Python and psutil to tap into your system‘s inner workings. We walked through monitoring CPU temperature, CPU usage, memory, disks, network, sensors, and more. Hopefully the code snippets and project ideas have sparked your imagination for ways you can use this knowledge in your own applications.

To recap, the key takeaways are:

  1. The psutil module provides cross-platform access to detailed system resource information from Python.

  2. Monitoring system resources is important for diagnosing performance issues, preventing problems, and optimizing your applications.

  3. Checking CPU temperature is a good way to stay on top of cooling issues and avoid thermal throttling or hardware damage.

  4. psutil can help you introspect running processes to understand their resource consumption.

  5. You can build some nifty tools with psutil like performance dashboards, automated alerts, data visualizations, and more.

I encourage you to download psutil and play around with it. Spend some time exploring the various functions and data they return. Try integrating psutil into your own projects. As you grow more familiar with it, you‘ll find yourself turning to it anytime you need to do something system-related from Python.

To learn more, check out the official documentation, peruse the source code on GitHub, and search for blog posts/tutorials covering specific use cases. There‘s a large community of Python developers using psutil, so you‘ll find no shortage of additional resources.

Go forth and conquer your system resources with Python and psutil! Let me know in the comments what cool projects you come up with.

Similar Posts