What's wrong with this Python code?

2

I'm trying to create a simple project for study purposes but I'm having trouble completing it. I am using the Pytube library to download videos, I can download the videos but I can not show the download progress bar and the size of the file (video) to download.

My code is this:

from pytube import YouTube
from pprint import pprint
from pytube import utils
from pytube.models import *

#Pede url do vídeo
url_video = str(input("URL do vídeo: "))

#Instancia a Classe.
yt = YouTube(url_video)

#Mostra o título do video + formato e resolução
print("\nTitulo do vídeo: ", yt.filename)
print("Formatos e Resoluções")

#Vai percorrer a Classe yt.get_videos formatos do vídeo e o tipo.
for i in yt.get_videos():
        print(i)

formato = str(input("\nQuais dos formatos a cima você deseja baixar seu vídeo(ex: .mp4 .3gp ): "))
resolucao = str(input("Digite qual das resoluções existente no video que você deseja baixar(ex: 720p): "))

print("\nVocê deseja renomear o nome do vídeo? Caso você diga queira o vídeo sera salvo com o nome padrão.\n")

perg = int(input("(1-Sim / 2-Não): "))

if perg == 1:
    nome = str(input("Digite o nome: "))
    yt.filename = nome

video = yt.get(formato, resolucao)
caminho = str(input("Caminho(ex: /usuario/Downloads/)>> "))
video.download(caminho)

I read the library documentation and went to the utils and models modules.

in the Utils module says the following:

Def  print_status ( progress , file_size ):
    -benzóico.
    Esta função - quando transmitida como 'on_progress' para' Video.download' - imprime
    O progresso de download atual.
    Argumentos:
    Progress - O comprimento dos bytes atualmente baixados.
    File_size - O tamanho total do vídeo.
    -benzóico.
    % = Progresso *  100 . / File_size
    Status =  r " % 10d   [ % 3.2f %% ] "  % ( progresso, porcentagem )
    Status = status +  chr ( 8 ) * ( len (status) +  1 )
    print status,

and no Models :

def download(self, path=None, chunk_size=8*1024,
             on_progress=None, on_finish=None):
    """
    Downloads the file of the URL defined within the class
    instance.
    Keyword arguments:
    path -- Destination directory
    chunk_size -- File size (in bytes) to write to buffer at a time
                  (default: 8 bytes).
    on_progress -- A function to be called every time the buffer was
                   written out. Arguments passed are the current and
                   the full size.
    on_finish -- To be called when the download is finished. The full
                 path to the file is passed as an argument.
    """

    path = (normpath(path) + '/' if path else '')
    fullpath = '%s%s.%s' % (path, self.filename, self.extension)
    response = urlopen(self.url)
    with open(fullpath, 'wb') as dst_file:
        meta_data = dict(response.info().items())
        file_size = int(meta_data.get("Content-Length") or
                        meta_data.get("content-length"))
        self._bytes_received = 0
        while True:
            self._buffer = response.read(chunk_size)
            if not self._buffer:
                if on_finish:
                    on_finish(fullpath)
                break

            self._bytes_received += len(self._buffer)
            dst_file.write(self._buffer)
            if on_progress:
                on_progress(self._bytes_received, file_size)

But even so reading I did not understand much. Someone to help me?

    
asked by anonymous 21.04.2017 / 16:30

1 answer

4

See the documentation for the download function:

"""
Downloads the file of the URL defined within the class
instance.
Keyword arguments:
path -- Destination directory
chunk_size -- File size (in bytes) to write to buffer at a time
              (default: 8 bytes).
on_progress -- A function to be called every time the buffer was
               written out. Arguments passed are the current and
               the full size.
on_finish -- To be called when the download is finished. The full
             path to the file is passed as an argument.
"""

There is a parameter called on_progress , which is a function that will be called every time the buffer is written to disk. This function will receive two parameters: the first refers to the current status of the transfer and the second the total size of the file.

The library itself already has a function for it, which is just print_status , so you just need to do the following:

video.download(caminho, on_progress=print_status)

If you need something more specific, you can create this function manually:

def my_print_status (current, fullsize):
    print("Transferido {} de {}".format(current, fullsize))

It may be necessary to format the parameters as needed, but the idea is this. The download call would be:

video.download(caminho, on_progress=my_print_status)
    
21.04.2017 / 18:48