How to dynamically update multiline output

I want to update some information dynamically (just like a progress bar), I can do it with the 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 information dynamically. When it adds '\ n' to the output, it cannot work as you expect.

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

Any way to help him update multi-page content?

+8
python
source share
4 answers

I also had this situation, and I finally got the idea to solve this problem: D

reprint - a simple module for Python 2/3 for printing and updating the contents of several lines in the terminal

You can simply treat this instance of output as a regular dict or list (depending on which mode you use). When you change this content in the output instance, the output in the terminal will automatically update: D

Here is an 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) 
+2
source share

You can do this with curses , but this is not trivial.

+1
source share

It is impossible to make this system independently (when using the "system" I mean not only the OS, but also the terminal application and its configuration), since there is no standard escape sequence that would move the cursor up. As for system-specific methods, they may exist for your configuration, but you need more information about your system. In general, it is usually not recommended to use such functions.

PS I hope you are not going to redirect the output of your program to a file. When redirected to a file, such progress indicators produce a terrible result.

0
source share

write '\ b' to the console:

 import sys import time print "start the output" def loop(): i = 0 output = "\rFirst_line%s..." % str(0) sys.stdout.write(output) while 1: sys.stdout.write('\b'*len(output)) i += 1 output = "\rFirst_line%s..." % str(i) sys.stdout.write(output) sys.stdout.flush() time.sleep(1) loop() 
-one
source share

All Articles