Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the multi-line output dynamically

Tags:

python

I want to refresh some info dynamically(just like progress bar), I can do it with following code

#! /usr/bin/env python
import sys
import time

print "start the output"
def loop():
    i = 0

    while 1:
        i += 1
        output = "\rFirst_line%s..." % str(i) 
        sys.stdout.write(output)        
        sys.stdout.flush()
        time.sleep(1)
loop()

It could only output single_line info dynamically, When add '\n' into output, It couldn't work as expect.

output = "\rFirst_line%s...\n" % str(i)

Any way could help it to refresh multi_line content?

like image 815
user1675167 Avatar asked Jan 13 '13 04:01

user1675167


2 Answers

I also had that situation, and I finally got a idea to solve this ;D

reprint- A simple module for Python 2/3 to print and refresh multi line output contents in terminal

You can simply treat that output instance as a normal dict or list(depend on which mode you use). When you modify that content in the output instance, the output in terminal will automatically refresh :D

Here is a example:

from reprint import output
import time
import random

print "start the output"

with output(initial_len=3, interval=0) as output_lines:
    while True:
        output_lines[0] = "First_line  {}...".format(random.randint(1,10))
        output_lines[1] = "Second_line {}...".format(random.randint(1,10))
        output_lines[2] = "Third_line  {}...".format(random.randint(1,10))
        time.sleep(0.5)
like image 150
Yinzo Avatar answered Oct 28 '22 13:10

Yinzo


You could do it with curses, but it's nontrivial.

like image 32
orip Avatar answered Oct 28 '22 12:10

orip