I am trying to make a code to download videos from YouTube using pafy
module and a progressbar using tqdm
module, however the progressbar is finished before the download complete.
here is my code download piece:
JavaScript
x
3
1
with tqdm.tqdm(desc=video_name, total=video_size, unit_scale=True, unit='B', initial=0) as pbar:
2
bestVideo.download(filepath=full_path, quiet=True, callback=lambda _, received, *args: pbar.update(received))
3
here is a pic a the progressbar:
https://i.stack.imgur.com/VMBUN.png
Advertisement
Answer
Problem is because pbar.update()
expects value current_received - previous_received
download
gives only current_received
so you have to use some variable to rember previous value and substract it
Minimal working code:
JavaScript
1
25
25
1
import pafy
2
import tqdm
3
4
# --- functions ---
5
6
previous_received = 0
7
8
def update(pbar, current_received):
9
global previous_received
10
11
diff = current_received - previous_received
12
pbar.update(diff)
13
previous_received = current_received
14
15
# --- main ---
16
17
v = pafy.new("cyMHZVT91Dw")
18
s = v.getbest()
19
20
video_size = s.get_filesize()
21
print("Size is", video_size)
22
23
with tqdm.tqdm(desc="cyMHZVT91Dw", total=video_size, unit_scale=True, unit='B', initial=0) as pbar:
24
s.download(quiet=True, callback=lambda _, received, *args:update(pbar, received))
25