开发者

How can I wait for a file to be uploaded (via ftp), then delete it?

开发者 https://www.devze.com 2023-01-04 20:58 出处:网络
Using Python, how can I wait for a file to be uploaded (using ftp) before deleting it? uploadFile(ftp, filepath,namef)

Using Python, how can I wait for a file to be uploaded (using ftp) before deleting it?

uploadFile(ftp, filepath,namef)
# ............Here, I need to wait........
os.remove(filepath)

A开发者_如何学Cny ideas?


Using the ftplib as linked by Randolpho, it looks like you want to use:

FTP.storbinary(command, file[, blocksize, callback])

Before you transfer the file, calculate how many blocks (of size blocksize it will take to transfer the file. Your callback function can count the number of times it is called and when the counter reaches the number of blocks, you know that the entire file has been transferred. Your callback function can then call the function that deletes the file.


Use ftplib to upload the file. The link I provided has many great examples for uploading files using FTP.

Use os.remove to delete the local file.


You could make a MD5 checksum, upload it, then download it, compare the MD5, and then delete if you have a match.
Bonus: if your server supports MD5 as a site extension, you don't have to download, you can just ask the server for the MD5.


You can use a callback function to check upload progress

import ftplib

ftp_uploadcomplete = False
ftp_blocksize = 1024
size_written = 0
total_size = len(myimg)

def handle(block):
    global size_written
    global total_size
    global ftp_blocksize
    size_written = size_written + ftp_blocksize if size_written + ftp_blocksize < total_size else total_size
    percent_complete = size_written / total_size * 100
    if (size_written==total_size):
        ftp_uploadcomplete = True
    print("%s percent complete" %str(percent_complete))

myftp = ftplib.FTP('host','login','pw')
myftp.storbinary("STOR file.jpg", myimg, callback=handle, blocksize=ftp_blocksize)

while (ftp_uploadcomplete==False):
    time.sleep(1)

print("Upload Done!")
0

精彩评论

暂无评论...
验证码 换一张
取 消