pgtoolkit/progresswrapper.py
changeset 34 98c7809af415
equal deleted inserted replaced
33:bd0beda49bcb 34:98c7809af415
       
     1 
       
     2 import sys
       
     3 
       
     4 
       
     5 class ProgressWrapper:
       
     6     
       
     7     def __init__(self, f, size=0):
       
     8         self.f = f
       
     9         self.size = size
       
    10         self.readsize = 0
       
    11         self.cycles = 0
       
    12         self.print_cycles = 200
       
    13 
       
    14     def humanize(self, bytes):
       
    15         if bytes > 1024**3:
       
    16             return '%.1fG' % (bytes / 1024.**3)
       
    17         if bytes > 1024**2:
       
    18             return '%.1fM' % (bytes / 1024.**2)
       
    19         if bytes > 1024:
       
    20             return '%.1fk' % (bytes / 1024.)
       
    21         return '%d' % bytes
       
    22 
       
    23     def write(self, data):
       
    24         self.size += len(data)
       
    25         if self.cycles == 0:
       
    26             print('  read %s      \r' % self.humanize(self.size), end='')
       
    27             sys.stdout.flush()
       
    28             self.cycles = self.print_cycles * 200
       
    29         else:
       
    30             self.cycles -= 1
       
    31         return self.f.write(data)
       
    32 
       
    33     def read(self, size):
       
    34         self.readsize += size
       
    35         if self.cycles == 0:
       
    36             if self.size > 0:
       
    37                 percent = self.readsize * 100. / self.size
       
    38             else:
       
    39                 percent = 100
       
    40             if percent > 100:
       
    41                 percent = 100
       
    42             print('  written %s / %s (%.1f%%)      \r' % (
       
    43                 self.humanize(self.readsize),
       
    44                 self.humanize(self.size),
       
    45                 percent), end='')
       
    46             sys.stdout.flush()
       
    47             self.cycles = self.print_cycles
       
    48         else:
       
    49             self.cycles -= 1
       
    50         return self.f.read(size)
       
    51 
       
    52     def close(self):
       
    53         self.f.close()
       
    54