Show FTP download progress in Python (ProgressBar)

后端 未结 1 784
旧巷少年郎
旧巷少年郎 2020-12-03 20:41

I am downloading files over FTP using the following Python script. What I wanted is to see the details of the progress while downloading. For that I used ProgressBar

相关标签:
1条回答
  • 2020-12-03 21:00

    You never update the ProgressBar. What you need to do is to:

    • Implement a function (or a class method) that you will pass to FTP.retrbinary as callback instead of file.write. The function should do file.write and also update the progress bar.

    • You also need to know size of the file/transfer for maxval argument of ProgressBar. For that you can use FTP.size.

    A trivial implementation is like:

    local_path = "archive.zip"
    remote_path = "/remote/path/archive.zip"
    
    file = open(local_path, 'wb')
    
    size = ftp.size(remote_path)
    
    pbar = ProgressBar(widgets=widgets, maxval=size)
    pbar.start()
    
    def file_write(data):
       file.write(data) 
       global pbar
       pbar += len(data)
    
    ftp.retrbinary("RETR " + remote_path, file_write)
    

    And now you get the progress bar you want:

    Downloading:  72% [###############################            ] ETA:   0:00:00 242.1 MiB/s
    

    Note for others: The OP code uses progressbar2 library.

    PyQt implementation: Update PyQt progress from another thread running FTP download.

    0 讨论(0)
提交回复
热议问题