From a66eb197c71bd2094c9b9e7c6c3e64f59bbb6fd1 Mon Sep 17 00:00:00 2001 From: Peter Williams Date: Fri, 2 Sep 2022 17:04:33 -0400 Subject: [PATCH] toasty/progress.py: add this --- toasty/progress.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 toasty/progress.py diff --git a/toasty/progress.py b/toasty/progress.py new file mode 100644 index 0000000..c02a04a --- /dev/null +++ b/toasty/progress.py @@ -0,0 +1,45 @@ +# -*- mode: python; coding: utf-8 -*- +# Copyright 2022 the AAS WorldWide Telescope project +# Licensed under the MIT License. + +"""Utilities for progress reporting + +This module provides an extremely thin wrapper around TQDM that avoids ``\r`` +output when stdout is not a terminal, for producing more easily greppable logs. +It also reduces the update frequency to reduce log volume. + +""" + +__all__ = """ +progress_bar +""".split() + +from contextlib import contextmanager +import sys + +from tqdm import tqdm + +NON_TTY_INTERVAL = 30 + + +@contextmanager +def progress_bar(total=None, show=None): + assert total is not None + assert show is not None + + args = dict( + total=total, + disable=not show, + ) + + if not sys.stdout.isatty(): + args["bar_format"] = "{l_bar}{bar}{r_bar}\n" + args["mininterval"] = NON_TTY_INTERVAL + args["maxinterval"] = NON_TTY_INTERVAL + + try: + with tqdm(**args) as progress: + yield progress + finally: + if show and sys.stdout.isatty(): + print()