Progress bar WIP

This commit is contained in:
Simon Willison 2020-10-26 21:37:19 -07:00
commit 4c1ed92c17
3 changed files with 42 additions and 5 deletions

View file

@ -1,4 +1,7 @@
import base64
import click
import contextlib
import io
import os
try:
@ -87,3 +90,29 @@ def find_spatialite():
if os.path.exists(path):
return path
return None
class UpdateReader(io.TextIOWrapper):
def __init__(self, raw, update):
super().__init__(raw)
self._update = update
def read(self, size=-1):
bytes = super().read(size)
self._update(len(bytes))
return bytes
def readline(self, size=-1):
bytes = super().readline(size)
self._update(len(bytes))
return bytes
@contextlib.contextmanager
def file_progress(file, silent=False, **kwargs):
if silent or file.raw.fileno() == 0: # 0 = stdin
yield file
else:
file_length = os.path.getsize(file.raw.name)
with click.progressbar(length=file_length, **kwargs) as bar:
yield UpdateReader(file, update=bar.update)