Python Ftp Timeout and Error Handling

Feb 22, 2021

Without timeout, it seeems like ftp might be stuck forever under certain network condition.

import socketfrom ftplib import FTP, error_tempfrom time import sleepHOST = ...USERNAME = ...PASSWORD = ...ftp = FTP(HOST, timeout=60*5)ftp.login(USERNAME, PASSWORD)local_path = ...remote_path = ...# download filewhile True:    try:         with open(local_path, 'wb') as file :            ftp.retrbinary(f"RETR {remote_path}", file.write)        break    except (error_temp, BrokenPipeError, socket.timeout) as e:        try_count += 1        if try_count > 3:            raise e        else:            print(e)            sleep(try_count * 2)

NOTE: Python FTP: List Files in Directory and Download

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.