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开发者_JAVA百科.)
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.
How about the progressbar package?
print "progress text\r",
Notice the trailing comma which suppresses new line.
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 = ' ')
精彩评论