Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you print multiple lines at once and carriage return them so they always stay in the same place?

I am writing a program where it gets current CPU utilisation from PSUtil, parses it, and displays it to the user.

def getAllCoreData_Parsed():
    output = ""

    for count, cpu in enumerate(ps.cpu_percent(percpu=True)):
        output += f"Core {count:<2}\t{cpu:>5}%\033[0;37;48m\n"


    return output



while True:
   print(
        getAllCoreData_Parsed(),
        end="\r"
    )


    time.sleep(1)


    print(
        "\x1b[K",
        end="\r"
    )

However, what I want it to do, it too replace all of the existing data with the new one without creating the newline OR showing it with the ‘tail’ of the previous write to the console.

What it is doing now is adding newlines where I haven’t told it too (Is it because of the \n used in the getAllCoreData_Parsed() function? I need that \n to format it as I need it displayed like such)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what it is currently doing:

Core 0    0.0%
Core 1    0.0%
Core 2    0.0%
Core 3    0.0%
Core 4    0.0%
Core 5    0.0%
Core 6    0.0%
Core 7    0.0%
Core 8    0.0%
Core 9    0.0%
Core 10   0.0%
Core 11   0.0%
Core 0    5.0%
Core 1    0.6%
Core 2    0.0%
Core 3    0.0%
Core 4    0.0%
Core 5    0.0%
Core 6    0.0%
Core 7    0.0%
Core 8    1.0%
Core 9    0.0%
Core 10   0.0%
Core 11   0.0%

This is what I want it to do:

Core 0    1.0%
Core 1    0.0%
Core 2    0.0%
Core 3    0.6%
Core 4    0.0%
Core 5    0.0%
Core 6    0.0%
Core 7    9.3%
Core 8    0.0%
Core 9    0.0%
Core 10   0.0%
Core 11   0.0%

AND THEN (same position on console)

Core 0    12.0%
Core 1    0.0%
Core 2    0.0%
Core 3    0.9%
Core 4    0.0%
Core 5    0.0%
Core 6    1.8%
Core 7    0.0%
Core 8    0.0%
Core 9    0.0%
Core 10   8.1%
Core 11   0.0%

Thanks

>Solution :

This should be what you’re looking for

import psutil
import time


def get_cpu_usage_by_core():
    return [
        f"Core {count:<2}\t{cpu:>5}%"
        for count, cpu in enumerate(psutil.cpu_percent(percpu=True))
    ]


while True:
    output = get_cpu_usage_by_core()

    for line in output:
        print(line)

    time.sleep(1)
    print("\033[F" * (len(output) + 1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading