Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Last active August 14, 2020 01:02
Show Gist options
  • Save miraculixx/7534e6dd20e41b1248db6535a67c021f to your computer and use it in GitHub Desktop.
Save miraculixx/7534e6dd20e41b1248db6535a67c021f to your computer and use it in GitHub Desktop.
a progress decorator for any python function
def progress(fn):
"""decorator to run fn until timeout in seconds, or wait forever if timeout < 0
Usage:
@progress
def fn(..):
return stop-flag, result
stopped, result = fn(.., timeout=SECONDS, stop_on_error=True|False, interval=SECONDS)
fn() will be called until stop-flag is true or timeout reached
"""
import tqdm
from time import sleep, time
from datetime import datetime as dt
def inner(*args, stop_on_error=False, timeout=-1, interval=1, ok=False, first=True, **kwargs):
start, elapsed, ok, result = dt.now(), 0, False, None
with tqdm.tqdm() as pbar:
while any((timeout == -1, timeout > elapsed)) or first:
pbar.update()
try:
ok, *result = fn(*args, pbar=pbar, **kwargs)
except Exception as e:
if stop_on_error:
raise
print("WARNING {}".format(str(e)))
first = sleep(interval) if not first else None
elapsed = (dt.now() - start).seconds
return ok, result
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment