-3

I would print the cpu usage with this simple python script. I would write the result, erase that row and re-write on the same line as like as windows shell does with some commands. Is it possible?

import psutil                                     #import tsutil
import time

def printit():
    while(1):
        print(psutil.cpu_percent())
        time.sleep(3)
printit()

This print line per line. I would the result always change on the same line

anky
  • 74,114
  • 11
  • 41
  • 70
edoardottt
  • 100
  • 1
  • 11

2 Answers2

1

yes, use print(psutil.cpu_percent(), end=' ')

you also need to flush stdout, because the content won't actaully be printed on screen unless you print a newline char.

try this:

import psutil
import time
import sys

def printit():
    while(1):
        print(psutil.cpu_percent(), end=' ')
        sys.stdout.flush()
        time.sleep(3)
printit()
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
1

Use carriage return on print function

import psutil
import time
import sys

def printit():
    while(1):
        print('{:06.2f}'.format(psutil.cpu_percent()), end='\r')
        time.sleep(3)
printit()

Updating: Using \r will break if the strings differ on size, format can fix this

geckos
  • 5,687
  • 1
  • 41
  • 53