-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
  • 71,373
  • 8
  • 36
  • 64
edoardottt
  • 92
  • 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
  • 11,623
  • 3
  • 23
  • 37
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
  • 4,912
  • 1
  • 34
  • 40