Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite output in terminal

Tags:

I have a Python script and I want to make it display a increasing number from 0 to 100% in the terminal. I know how to print the numbers on the terminal but how can I "rewrite" them so 0 turns into 1, 1 into 2, and so on until 100?

like image 626
jarkam Avatar asked Aug 15 '10 18:08

jarkam


1 Answers

Printing a carriage return (\r) without a newline resets the cursor to the beginning of the line, making the next print overwriting what's already printed:

import time import sys for i in range(100):     print i,     sys.stdout.flush()     time.sleep(1)     print "\r", 

This doesn't clear the line, so if you try to, say, print decreasing numbers using this methods, you'll see leftover text from previous prints. You can work around this by padding out your output with spaces, or using some of the control codes in the other answers.

like image 166
Benjamin Wohlwend Avatar answered Oct 02 '22 13:10

Benjamin Wohlwend