Codementor Events

Realtime CPU monitor using PyGame & Hooman

Published Nov 30, 2020
Realtime CPU monitor using PyGame & Hooman

Here’s a recipe showing a realtime CPU monitor using PyGame and the Hooman lib, which simplifies PyGame coding. It's purpose is to get someone started quickly with something interesting The line chart accepts arguments in as (x, y, width, height). As for

    {
            "data": graph_data,
            "mouse_line": True,
            "range_y": [0, max_cycle],
            "range_x": [0, max_time],
        }

mouse_line means the interactive cross-hair in the position of your mouse.

Of note is the line

range_data = list(zip(*graph_data ))

which transforms a list of [[1, 10], [2, 20], [3, 30]] into [[1, 2, 3], [10, 20, 30]] so that we can get the maximum value of each axis and adjust the range accordingly

Snippet

'''
Author: https://github.com/Abdur-rahmaanJ
Instructions: 
    pip install psutil hooman==0.3.6
'''

from hooman import Hooman
import psutil
import pygame

window_width, window_height = 500, 500
hapi = Hooman(window_width, window_height)

bg_col = (255, 255, 255)

loop_var = 0
time_unit = 0
graph_data = []

hapi.stroke_size(3)
hapi.stroke(hapi.color['black'])

while hapi.is_running:
    loop_var += 1
    hapi.background(bg_col)

    if loop_var % 10 == 0:
        time_unit += 1
        graph_data.append([round(time_unit), round(psutil.cpu_percent())])
        #print(graph_data)

    if graph_data:
        range_data = list(zip(*graph_data ))
        max_time = round(max(range_data[0]))
        max_cycle = round(max(range_data[1]))
    else:
        max_time = 100
        max_cycle = 100

    hapi.linechart(
        30,
        30,
        400,
        300,
        {
            "data": graph_data,
            "mouse_line": True,
            "range_y": [0, max_cycle],
            "range_x": [0, max_time],
        },
    )

    hapi.event_loop()
    hapi.flip_display()

pygame.quit()

output:
pygame_hooman_spu cyles.png

Discover and read more posts from Abdur-Rahmaan Janhangeer
get started
post commentsBe the first to share your opinion
Show more replies