0

I am trying to write a decorator that will print dots in terminal while the function that calls the decorator executes.

import sys
from time import sleep


def call_counter(func):
    def helper(*args, **kwargs):
        for dot in xrange(0, 99):
            sys.stdout.write(".")
            sys.stdout.flush()
        return func(*args, **kwargs)
    helper.calls = 0
    helper.__name__= func.__name__
    return helper

@call_counter
def f():
    sleep(10)



if __name__ == "__main__":
    f()

this is what I have tried so far. But i am not getting expected result. for function taking time to execute I have used sleep of 10 seconds .

Chang Zhao
  • 631
  • 2
  • 8
  • 24

1 Answers1

0

Whether you use decorators or not you cannot magically print the progress of a function without having this function willingly reporting its progress. Reporting the progress is usually done by passing a progress callback to the function. The function will at eg each iteration of an internal loop (provided it has some sort of loop) execute the user callback and pass a parameter denoting its current progress. something like

def long_func(data:list, progress):
tot = len(data)
for i,item in enumerate(data):
   #do something with item
   progress(i+1/tot)
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • in my long running function actually make call to a `subprocess.Popen` that takes long time not that there is something iterative that takes time. if it was an iterative I could have easily printed the progress and this post on SO wouldnt have existed. – Chang Zhao Jul 18 '20 at 21:15