Check if any file was downloaded in Paramiko recursive file transfer

Viewed 72

I'm not able to figure out why cannot get exit code 1 in this function when item or item.filename which is the absolute path to file is empty ?

def sftp_get_recursive(path, dest, sftp):
    item_list = sftp.listdir_attr(path)
    dest = str(dest)
    if not os.path.isdir(dest):
        os.makedirs(dest, exist_ok=True)
    for item in item_list:
        mode = item.st_mode
        if not str(item) :
           print(item.filename)
           print("No file found")
           sys.exit(1)
        elif S_ISDIR(mode):
           sftp_get_recursive(path + "/" + item.filename, dest + "/" + item.filename, sftp)
        else:
           sftp.get(path + "/" + item.filename, dest + "/" + item.filename)
           print("Sending file from : ",path + "/" + item.filename)
           sftp.remove(path + "/" + item.filename)
1 Answers

If you want to return specific exit code, if there is no file anywhere in the directory tree, you will have to recursively count the files.

def sftp_get_recursive(path, dest, sftp):
    count = 0
    item_list = sftp.listdir_attr(path)
    if not os.path.isdir(dest):
        os.makedirs(dest, exist_ok=True)
    for item in item_list:
        source_path = path + "/" + item.filename
        dest_path = os.path.join(dest, item.filename)
        if S_ISDIR(item.st_mode):
           count += sftp_get_recursive(source_path, dest_path, sftp)
        else:
           print("Sending file from : ", source_path)
           sftp.get(source_path, dest_path)
           sftp.remove(source_path)
           count += 1
    return count

(I have refactored your code a bit to avoid repeating code)

And then use the count at the top level:

count = sftp_get_recursive(path, dest, sftp)
if count == 0:
    print("No file found")
    sys.exit(1)

Note that even if no files are found, the code will still recreate the empty remote directory structure locally. I'm not sure, if that's what you want.

Related