Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script to show progress?

I would like show progress to user when my python script processing a big file.

I have seen script printings '\', "|', '/' in the same cursor position in the shell to show progress.

How can I do that in python?

like image 465
michael Avatar asked Nov 22 '12 22:11

michael


4 Answers

A simple "infinite spinner" implementation:

import time
import itertools

for c in itertools.cycle('/-\|'):
    print(c, end = '\r')
    time.sleep(0.2)
like image 130
barracel Avatar answered Nov 14 '22 18:11

barracel


You should use python-progressbar

It's as simple to use as:

import progressbar as pb

progress = pb.ProgressBar(widgets=_widgets, maxval = 500000).start()
progvar = 0

for i in range(500000):  
    # Your code here
    progress.update(progvar + 1)
    progvar += 1

This will show a progress bar like:

Progress: |####################################################            |70%
like image 21
zaynyatyi Avatar answered Nov 14 '22 19:11

zaynyatyi


tqdm is a more powerful one for this case. it has better features and comparability.

it is easy for usage, the code could be simple as:

from tqdm import tqdm
for i in tqdm(range(10000)):
    pass  # or do something else

customization is also easy for special cases.

here is a demo from the repo:

like image 5
jerliol Avatar answered Nov 14 '22 19:11

jerliol


If you want to roll your own, you can do something like this:

import sys, time

for i in range(10):
  print ".", # <- no newline
  sys.stdout.flush() #<- makes python print it anyway
  time.sleep(1)

print "done!"

This'll print one dot every second and then print "done!"

like image 2
Rachel Sanders Avatar answered Nov 14 '22 19:11

Rachel Sanders