Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中恢复中断的FTP上载_Python_Python 3.x_Ftp_Ftplib - Fatal编程技术网

如何在Python中恢复中断的FTP上载

如何在Python中恢复中断的FTP上载,python,python-3.x,ftp,ftplib,Python,Python 3.x,Ftp,Ftplib,我需要手动中断am FTP上传,然后测试我是否可以恢复上传。我正在使用Python的ftplib模块。 我尝试了以下代码: # Consider I have logged in using valid ftp user # File is of 20 MB counter = 0 file_name = 'test.dat' ftp_dir = 'test_ftp_dir' with open(file_address, 'rb') as file: ftp.set_debuglev

我需要手动中断am FTP上传,然后测试我是否可以恢复上传。我正在使用Python的ftplib模块。 我尝试了以下代码:

# Consider I have logged in using valid ftp user
# File is of 20 MB
counter = 0
file_name = 'test.dat'
ftp_dir = 'test_ftp_dir'

with open(file_address, 'rb') as file:
    ftp.set_debuglevel(2)
    ftp.cwd(ftp_dir)
    ftp.voidcmd('TYPE I')
    with ftp.transfercmd(f'STOR {file_name}', None) as conn:
        while True:
            # Read 1 MB
            buf = file.read(1000000)
            if not buf:
                break
            conn.sendall(buf)
            counter += 1
            if counter == 5:
                # Stop after 5 MB
                LOG.info("STEP-3: Abort client transfer")
                break

# Reading file again and logging again using the ftp user
with open(file_address, 'rb') as file:
    ftp.set_debuglevel(2)
    ftp.cwd(ftp_dir)
    ftp.voidcmd('TYPE I')
    ftp.storbinary(f'STOR {file_name}', file, rest=ftp.size(file_name))

它不是从5MB重新启动上载,而是在将完整文件追加到原始文件的同时发送完整文件。假设我发送了5 MB的文件,那么我可以看到5 MB的文件,当我尝试恢复它时,它会发送整个20 MB的文件,使其成为一个总共25 MB的文件。请帮我做这个。谢谢。

在开始传输之前,您必须将源本地文件搜索到重新启动位置:

# Reading file again and logging again using the ftp user
with open(file_address, 'rb') as file:
    rest = ftp.size(file_name)
    file.seek(rest)
    ftp.cwd(ftp_dir)
    ftp.storbinary(f'STOR {file_name}', file, rest=rest)
ftplib不会为您查找该文件,这将限制其使用。有些情况下,你不希望它去寻找。还有一些类似文件的对象不支持查找


有关可恢复FTP上载的完整代码,请参阅: