Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

python - ftplib - download with showing hash mark on screen and be able to interrupt anytime

I want to use ftplib to download a file.

import ftplib

class Ftp:
  def start(self):
    self.ftp = ftplib.FTP('speedtest.tele2.net')
    self.ftp.login()
    with open('1GB.zip', 'wb') as f:
      result = self.ftp.retrbinary('RETR 1GB.zip', f.write)

  def stop(self):
    self.ftp.sock.close()

My first question is, when I call start(), I can see there is a file in File Explorer which its size is keep growing up. However, nothing on the screen. How can I call print('#', end='') while downloading? Like the following pic.

enter image description here

Second. When I call stop(), there is nothing happened because the file size is keep growing up. I've also try self.ftp.abort() but it will hang the whole process. How can I stop the downloading process at any time?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As soon as you call the start method and call retrbinary, the execution thread will get stuck in there until the download completes. You can do nothing during that time.

Check if the FTP library allows to pass a callback function that you can then use to show progress.

The alternative is to use a FTP library that support asyncio which will free the main thread and allow you to display progress or do other things while the file download.

The other solution that is not as clean is to use multiprocessing that will start an entire new Python process to execute your start method. Meanwhile you can use the main process to show progress.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...