简体   繁体   中英

Python FTP retrieve breaks the FOR loop. I fixed it with try-catch block. Why does it work?

I am connecting to some robots in my workplace via FTP protocol to gather the backup data automatically. Script should iterate through all the folders and download all the files inside. However when I run the code below, the python script leaves for folder in Folder_List: loop after first iteration. It's weird because when I tried to see what causes the bug by entering these commands in terminal, everything went through without an error.

After commenting parts of the code here I found out that the line ftp.retrbinary('RETR '+ filename, file.write) causes the loop to break. In the robot os the parent folder is "/ROBOT" and other folders are inside like this: "/ROBOT/JOB" or "/ROBOT/DAT"

from ftplib import FTP
import os
import os.path

try:
    ftp = FTP('192.10.100.1')
    ftp.login('user', 'password')
    ftp.getwelcome()
    ftp.cwd('ROBOT/')

    save_dir_full = '/home/mint/Documents/robot_data'
    Folder_List = ftp.nlst()
    # Folder_List should be similar to this: 
    # Folder_List = ['JOB', 'DAT', 'CND', 'SYS', 'PRM', 'LST', 'CSV', 'LOG']

    for folder in Folder_List:
        if not(os.path.exists(save_dir_full +'/'+folder)):
            try:
                os.makedirs(save_dir_full +'/'+folder)
            except:
                #print('directory already exists')
                pass
        ftp.cwd(folder)
        filenames = ftp.nlst() # get filenames within the directory
        for filename in filenames:
            local_filename = os.path.join(save_dir_full +'/'+folder+'/'+ filename)
            file = open(local_filename, 'wb')

            # THERE \/
            ftp.retrbinary('RETR '+ filename, file.write)

            file.close()
            print(filename)
                
        ftp.cwd('..')

    ftp.quit()
                
except:
    print('Could not connect to ftp device')

After I added the try block, the loop did not break and the program finishes with success:

try:
    ftp.retrbinary('RETR '+ filename, file.write)
except:
    pass

Do you have any ideas why it worked?

Do you have any ideas why it worked?

First thing to do is to take closer look at what happend, to do this, replace:

try:
    ftp.retrbinary('RETR '+ filename, file.write)
except:
    pass

with

try:
    ftp.retrbinary('RETR '+ filename, file.write)
except Exception as e:
    print(e)

and observe would your code will produce. As more general note usage of bare except , is not recommended in python .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM