ftplib - Python:脚本在下载大文件时挂起

时间:2017-01-26 17:46:40

标签: python ftplib

Backstory是我试图从我给出的ftp登录中提取一些数据。这些数据每天都会不断更新,我相信他们会在每周或每月结束时擦除ftp。我正在考虑输入日期并每天运行脚本以查看是否有任何文件与日期匹配,但如果服务器时间不准确,则可能导致数据丢失。现在我只想下载所有文件,然后再努力进行微调。

我以前编写ftp的工作并不多,但看起来很简单。但是,我遇到的问题是小文件下载没有问题,他们的文件大小检查和匹配。当它试图下载一个通常需要几分钟的大文件时,它会到达某个点(几乎完成文件),然后它就会停止并且脚本会挂起。

例如:

它尝试下载大小为373485927字节的文件。该脚本运行并下载该文件,直到373485568字节。在尝试不同的方法并更改一些代码后,它总是停在这个数量上。

不明白为什么它总是停在这个字节以及为什么它可以适用于较小的文件(1000字节及以下)。

import os
import sys
import base64
import ftplib

def get_files(ftp, filelist):
    for f in filelist:
        try:
            print "Downloading file " + f + "\n"
            local_file = os.path.join('.', f)
            file = open(local_file, "wb")
            ftp.retrbinary('RETR ' + f, file.write)
        except ftplib.all_errors, e:
            print str(e)

        file.close()
    ftp.quit()

def list_files(ftp):
    print "Getting directory listing...\n"
    ftp.dir()
    filelist = ftp.nlst()
    #determine new files to DL, pass to get_files()
    #for now we will download all each execute
    get_files(ftp, filelist)

def get_conn(host,user,passwd):
    ftp = ftplib.FTP()
    try:
        print "\nConnecting to " + host + "...\n"
        ftp.connect(host, 21)
    except ftplib.all_errors, e:
        print str(e)

    try:
        print "Logging in...\n"
        ftp.login(user, base64.b64decode(passwd))
    except ftplib.all_errors, e:
        print str(e)

    ftp.set_pasv(True)

    list_files(ftp)

def main():
    host = "host.domain.com"
    user = "admin"
    passwd = "base64passwd"

    get_conn(host,user,passwd)

if __name__ == '__main__':
    main()

输出看起来像这样,文件dddd.tar.gz是最重要的,永远不会完成它。

下载文件aaaa.del.gz

下载文件bbbb.del.gz

下载文件cccc.del.gz

下载文件dddd.tar.gz

2 个答案:

答案 0 :(得分:0)

这可能是由超时问题引起的,也许可以尝试:

def get_conn(host,user,passwd):
    ftp = ftplib.FTP()

添加更大的超时,直到你有更多的想法,例如:

def get_conn(host,user,passwd):
    ftp = ftplib.FTP(timeout=100)

我不确定ftplib是否默认为超时,如果您正在从服务器超时,那么值得检查并值得检查。希望这会有所帮助。

答案 1 :(得分:0)

如果您在Windows cmd控制台中运行scrpit,请尝试禁用" QuickEdit模式"选项 cmd

我遇到了一个问题,即我的ftp脚本在Windows中运行,但在linux中正常运行。最后我发现解决方案对我有用。

价:enter link description here