]> code.delx.au - youtube-cgi/blobdiff - youtube.cgi
improved CLI status display
[youtube-cgi] / youtube.cgi
index 5e612d4084dd1f22ccc5d884dffefdd0ef2ec7f5..f5845a4e9e95d424abc972895e94e11994f1bf86 100755 (executable)
@@ -238,27 +238,32 @@ def pp_size(size):
 
 def copy_with_progress(content_length, infile, outfile):
        def print_status():
+               rate = 0
+               if now != last_ts:
+                       rate = last_bytes_read / (now - last_ts)
                sys.stdout.write("\33[2K\r")
                sys.stdout.write("%s / %s (%s/sec)" % (
                        pp_size(bytes_read),
                        pp_size(content_length),
-                       pp_size(bytes_read / (now - start_ts)),
+                       pp_size(rate),
                ))
                sys.stdout.flush()
 
-       start_ts = time.time()
        last_ts = 0
+       last_bytes_read = 0
        bytes_read = 0
        while True:
                now = time.time()
                if now - last_ts > 0.5:
-                       last_ts = now
                        print_status()
+                       last_ts = now
+                       last_bytes_read = 0
 
                buf = infile.read(32768)
                if not buf:
                        break
                outfile.write(buf)
+               last_bytes_read += len(buf)
                bytes_read += len(buf)
 
        # Newline at the end
@@ -298,7 +303,7 @@ def main():
 
                try:
                        copy_with_progress(content_length, video_data, outfile)
-               except IOError:
+               except IOError, e:
                        print
 
                video_data.close()
@@ -308,7 +313,8 @@ def main():
                        if old_offset == offset:
                                time.sleep(1)
                        print "Restarting download from", pp_size(offset)
-                       continue
+               else:
+                       break
 
        outfile.close()