Reputation: 7709
Python does not continue to replace the same line in the terminal, but it replaces "name" and adds the progress bar to a new line which results in a huge stack of progress bars...this only happens when I use "\n" before "name". How can I get the result to look like this?
[### ] 4%
name2
python
mylist = ['name1', 'name2', 'name3',...'name66']
for name in mylist:
sys.stdout.write('\r[%-66s] %d%%' % ('#'*prog, (prog*1.51515151515))+'\n'+name)
sys.stdout.flush()
Upvotes: 0
Views: 133
Reputation: 6311
You can achieve this by using enough blank spaces too look like a new line, but not actually use the newline character. Then use the backspace character \b
to move your cursor back to the beginning of the line and overwrite all that you wrote.
I extended your example a bit to make it a runnable script, by throwing a sleep in there and manually incrementing prog
.
import sys
from time import sleep
import os
# Get the number of columns in the terminal
rows, columns = os.popen('stty size', 'r').read().split()
columns = int(columns)
mylist = ['name1', 'name2', 'name3','name4']
prog = 0
for name in mylist:
prog += 10
bar = '[%-66s] %d%%' % ('#'*prog, (prog*1.51515151515))
spaces_left = columns-len(bar)
sys.stdout.write(bar+(" "*spaces_left)+name+('\b'*(len(name) + columns)))
sys.stdout.flush()
sleep(.5)
Upvotes: 1
Reputation: 6895
You could try progressbar for this. It works well and is easy to configure in my experience.
Upvotes: 2