How To Use Python To Monitor Your Mac Resources

Introduction

How To Use Python To Monitor Your Mac Resouces (Temp, CPU, Mem, Load)
Python Mac Monitor Code

Today we will discuss on everything you need to know about How To Use Python To Monitor Your Mac Resources in simple and easy to follow guide.

Did you know that Python has a rich library set that offers extensive system monitoring capabilities?

Today I will break down three different ways on how to accomplish this task.

  • Go over what library we will use
  • Implement example code with fully working example
  • Break down things such as monitoring resources:
    • Temprature
    • CPU
    • Load
    • Memory usage

I have been working in the Software industry for over 23 years now and I have been a software architect, manager, developer and engineer. I am a machine learning and crypto enthusiast with emphasis in security. I have experience in various industries such as entertainment, broadcasting, healthcare, security, education, retail and finance.

If you would like to have your own system monitoring script for Mac that’s written in a lightweight way for Python, this article is for you. I will walk you through how we are going to code this.

All the code discussed in this document can be found in my Github repo here.

How To Install Package Dependencies For Monitoring Mac

First we will go over how to setup the packages in your system in order to be able to run the monitoring script for your Mac. As a note this script would probably work without modification on all variants and versions of Mac computers as it’s written in Python.

Installing Virtualenv

The first thing we need to do is setup our virtual environment application which will containerize the Python PIP packages. In order to do that make sure you have the following dependencies in your system:

  • Python 3
  • PIP 3

Then simply invoke the install command as shown below:

main alex@diamesos ~/code/python-mac-monitor > pip install virtualenv
Collecting virtualenv
  Downloading virtualenv-20.10.0-py2.py3-none-any.whl (5.6 MB)
     |████████████████████████████████| 5.6 MB 2.6 MB/s
Collecting backports.entry-points-selectable>=1.0.4
  Downloading backports.entry_points_selectable-1.1.1-py2.py3-none-any.whl (6.2 kB)
Collecting platformdirs<3,>=2
  Downloading platformdirs-2.4.0-py3-none-any.whl (14 kB)
Collecting six<2,>=1.9.0
  Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting filelock<4,>=3.2
  Downloading filelock-3.4.0-py3-none-any.whl (9.8 kB)
Collecting distlib<1,>=0.3.1
  Downloading distlib-0.3.4-py2.py3-none-any.whl (461 kB)
     |████████████████████████████████| 461 kB 9.3 MB/s
Installing collected packages: six, platformdirs, filelock, distlib, backports.entry-points-selectable, virtualenv
Successfully installed backports.entry-points-selectable-1.1.1 distlib-0.3.4 filelock-3.4.0 platformdirs-2.4.0 six-1.16.0 virtualenv-20.10.0

Once the package is installed you should now have the virtualenv command in your system path so we can proceed with the next step.

Activate Virtual Environment

Now that we have virtualenv we can proceed into creating and activating a virtual environment. This will allow us to install Python PIP packages in your system without installing the globally so when finished you can easily remove them by deleting the virtual environment we create.

In order to do this simply follow the command as shown below. In this case we are naming our virtual environment as venv.

main alex@diamesos ~/code/python-mac-monitor > virtualenv venv
created virtual environment CPython3.9.9.final.0-64 in 186ms
  creator CPython3Posix(dest=/Users/alex/code/python-mac-monitor/venv, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/alex/Library/Application Support/virtualenv)
    added seed packages: pip==21.3.1, setuptools==58.3.0, wheel==0.37.0
  activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
main alex@diamesos ~/code/python-mac-monitor > source venv/bin/activate

Now that the virtual environment is created and activated we can proceed into install our Python package dependencies.

Python Package Dependencies

In this case we will be leveraging a package called psutil which can be found here. With psutil you can basically perform all the system queries we need to monitor our Mac computer. This will allow us among other things to:

  • Get CPU Usage
  • Get Memory Usage
  • Find running proceses
  • Get the Load Average of the computer

In order to install psutil issue the command as shown below while your virtual environment is activated.

main (venv) alex@diamesos ~/code/python-mac-monitor > pip install psutil
Collecting psutil
  Using cached psutil-5.8.0-cp39-cp39-macosx_12_0_arm64.whl
Installing collected packages: psutil
Successfully installed psutil-5.8.0

If you see a successful message like above it means the package was installed correctly and it’s ready for us to use in our code.

How To Get Mac Memory

The first thing we will do is write some sample code on getting the Mac memory. In particular the virtual memory as this is how the system recognizes and uses it internally. The command to invoke to help us do this is the virtual_memory function.

>>> psutil.virtual_memory()
svmem(total=34359738368, available=18182520832, percent=47.1, used=15250898944, free=3259121664, active=13213040640, inactive=13710065664, wired=2037858304)

Once invoked it will give us various bits of information but the ones we care about the most are the following:

  • Total: This is the total memory your system has
  • Used: This simply indicates how much memory you are currently using
  • Free: This is how much free memory you have available to use in your system
  • Percent: This is just a convenience thing that shows you how much percentage wise your available memory is.

How To Get Mac Load average

The next task we will be visiting is getting your Mac’s load average. This is an indicator on how ‘busy’ your system is at the time it is being executed. It has been used historically as an overall average indicator taking into account various variables rather than looking independently things such as:

  • CPU Usage
  • Memory
  • GPU Usage
  • Disk Usage

It just generally tells you how much work is actually being undertaken by your system regardless of the resources being occupied.

>>> psutil.getloadavg()
(1.72412109375, 1.54931640625, 1.4892578125)

The execution of it is using the getloadavg function. This simply shows the three statistics, what you need to know is that if this number is exceeding 6-7 then the system is under some stress and if it’s higher than 8 then there’s a heavy workload of tasks being processed. Do note while this is a general abstraction it always correlates to the resources that it will be occupying in your system. This could be simply CPU but it can also be a combination of things such as CPU, GPU or CPU and Memory etc. So to have an overall better picture of what is happening it’s always good to monitor those things independently too.

How To Get Mac CPU percent

One important factor of monitoring is knowing your CPU usage of your system. This includes both the overall CPU usage and individual core usage to see how the distribution of the load is. In order to do this we will be leveraging the cpu_percent function of the psutil package.

>>> psutil.cpu_percent()
6.1
>>> psutil.cpu_percent(percpu=True)
[33.6, 33.4, 5.2, 2.3, 0.8, 0.3, 0.6, 0.2, 0.0, 0.0]

The commands above show two different use cases:

  • The first command runs and gives you the overall cpu usage from your processors combined
  • The second one that has the percpu parameter set to True allows you to see the usage per CPU core separately so you can see if your system is stress loading in one specific process or not.

If you combine the information of the CPU usage and the load average that we saw earlier in this article you should be able to get a good idea if your system is under load and some process has been hanging.

Get Process List By CPU

One last important bit of information we need to know about the system is getting the process listing and how much CPU each of them consumes. So lets say you now have found that your system load is high and the CPU usage is also high and you need to identify which program in your system is causing this problem the way to do it is by enumerating all the running processes (programs) in your system. Once you enumerate all of them you should see a CPU usage next to each of them with the code that we will use below. This will let you identify which one is problematic so you can go ahead and kill it if needed (either using Activity or from the command line using the kill command).

It’s important when trying to know How To Use Python To Monitor Your Mac Resources to also understand the details of your processes internally on your system.

To do this we need to write a bit more code than before such as first getting a process iterator and then iterating through every result until we exhaust it. The iterator basically gives us a process object which contains various attributes that are useful to us. In this case we will be getting the process name and the cpu percentage of each of them calling the as_dict helper function.

>>> process_list = []
>>> for process in psutil.process_iter():
...     process_info = process.as_dict(attrs=['name', 'cpu_percent'])
...     process_list.append(process_info)
>>> import pprint
>>> pprint.pprint(process_list)
[{'cpu_percent': 0.0, 'name': 'kernel_task'},
 {'cpu_percent': 0.0, 'name': 'launchd'},
 {'cpu_percent': 0.0, 'name': 'logd'},
...
]

As you can see we received a list of all the running processes (abbreviated the list for demonstration reasons). Now you can easily observe the ones that have a high CPU usage and kill them if necessary. If you extend the code you can add if conditions for example to only print processes that have a CPU usage over 50%, in this case above 0.5.

Putting it all together in one script

As a final note we will be putting together all the code we write which you can find as one script in the Github here. One thing that we added was make the above into  functions and from there we added them in a loop with a polling interval. As mentioned earlier the full source can be found on the Github repo. The looping allows you to periodically check your system without flooding it with requests repeatedly over short periods of time. The default value we set it to is 5 seconds which is pretty generous for resource monitoring. If you want more prompt results you can easily adjust the POLL_INTERVAL value.

Learning How To Use Python To Monitor Your Mac Resources is helpful as it may allow you to extend it in more ways than you can think, I added some bonus points in the conclusion section below.

Finally if we were to execute we will be seeing a similar output to what we did earlier but just more compiled into one file for simplicity and full monitoring capabilities.

main (venv) alex@diamesos ~/code/python-mac-monitor > python ./mac-monitor.py
Process Listing:
{'cpu_percent': 0.1, 'name': 'kernel_task'}
{'cpu_percent': 0.0, 'name': 'launchd'}
{'cpu_percent': 0.0, 'name': 'logd'}
....
{'cpu_percent': 0.0, 'name': 'Python'}
CPU Usage:  28.6
All CPU Cores:  [33.3, 50.0, 100.0, 50.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0]
Memory:  svmem(total=34359738368, available=16765911040, percent=51.2, used=16666476544, free=1759494144, active=14631567360, inactive=13743554560, wired=2034909184)
Load Average:  (1.40869140625, 1.4130859375, 1.47021484375)

Conclusion

If you found How To Use Python To Monitor Your Mac Resources useful and you think it may have helped you please drop me a cheer below I would appreciate it.

If you have any questions, comments please post them below I check periodically and try to answer them in the priority they come in. Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.

The psutil library offers a lot of other useful functions that you may find useful in your resource system checking. Some functions note worth mentioning here are:

  • sensor_tempratures: This shows you the temperature of your system
  • sensors_battery: This shows you the battery status of your system
  • disk_usage: This lets you monitor the hard drive usage of your system

What app or library do you use to monitor your CPU usage?

I personally like to use iStats as it has worked well for me over the years and it’s feature rich, the feature I like the most is that it allows me to select explicitly which widgets to use in my menu bar which has limited space, this is a space saver!

If you would like to learn more about automation you can take a look at some of my articles here:

Leave a Comment

Your email address will not be published. Required fields are marked *