Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Python console program can output like the top command in Linux?

Tags:

python

The output of top command in Linux like bellow:

Tasks: 158 total, 1 running, 157 sleeping, 0 stopped, 0 zombie Cpu(s): 6.3%us, 3.2%sy, 0.0%ni, 89.9%id, 0.2%wa, 0.0%hi, 0.2%si, 0.0%st Mem: 8264212k total, 2637492k used, 5626720k free, 299884k buffers Swap: 4192924k total, 0k used, 4192924k free, 2010332k cached

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
7178 mysql 15 0 52876 31m 4680 S 21.3 0.4 308:12.04 mysqld
2262 www 16 0 28092 11m 4764 S 4.0 0.1 2:02.31 php-cgi
2110 www 16 0 27956 11m 4888 S 3.7 0.1 2:04.51 php-cgi
2005 www 16 0 28680 12m 4872 S 3.0 0.2 2:04.10 php-cgi
1955 www 16 0 28476 12m 5220 S 2.7 0.1 2:06.51 php-cgi
2030 www 16 0 28260 11m 4872 S 2.0 0.1 2:05.27 php-cgi
7044 www 15 0 24348 19m 932 S 0.7 0.2 1:58.38 nginx

Only part of the content changes constantly.

I can only output a single line keeps changing constantly without newline:

import  sys
import  time

if __name__ == '__main__':
    i = 0
    while True:
        sys.stdout.write('i = %d.\r' % i)
        sys.stdout.flush()
        time.sleep(1)
        i += 1

I want to know how to output multiline like the top command(keeps changing constantly without newline).

Sorry, My English is poor. Hope that makes sense.

Thanks, Qi

like image 555
redice Avatar asked Dec 17 '11 15:12

redice


1 Answers

You will need to use a library for handling the interaction with the console, e.g. http://docs.python.org/howto/curses.html

like image 75
Jeremy Avatar answered Oct 26 '22 17:10

Jeremy