Reputation: 28716
I don't know the right terms, so it is a bit hard to search how I can achieve this.
Commandline programs normally just print lines of text. Sometimes however, the text is updated. Good examples are git pull
or wget
.
As example:
[> ] 25%
[-> ] 50%
[--> ] 75%
[--->] 100%
But then on the same line changing over time.
How can I make this kind of thing in Python? It doesn't have to be more complicated than this, I just want to make status bars...
(I want this to work at least on Ubuntu, but cross-platform is the nicest.)
Upvotes: 1
Views: 1812
Reputation: 219
This Code also works in Google Colab
import time
for i in range(1, 101):
print('-' , end = ' ')
print(i , end = ' ')
time.sleep(0.5)
print('\r',end = ' ')
print('-' , end = ' ')
print(i , end = ' ')
Upvotes: 0
Reputation: 4244
print "progress text\r",
Notice the trailing comma which suppresses new line.
Upvotes: 0
Reputation: 129764
The magic is in \r
character, a.k.a. carriage return, a.k.a. go back to the beginning of the current line.
from __future__ import print_function
import time
for i in xrange(1, 100):
print('[{0:10}]'.format('-' * (i / 10)), end = '\r')
time.sleep(0.1)
There are also more advanced ways to manage the output to the console (through Console API on Windows, or ANSI escape codes) — they allow you to freely move the cursor and change text attributes like colour.
Upvotes: 3