尝试除了传递功能不继续

时间:2015-04-14 15:28:11

标签: python python-2.7 exception ftp try-catch

所以我需要帮助传递我的异常并继续我的其余脚本。简短的背景故事是我需要在ftp服务器上获得第一个400kb的文件,它有我需要的+ CONTENTS文件夹。我预计文件末尾会丢失一个错误,因为我在文件完成之前终止了ftp连接。在我的测试中,我可以终止ftp连接,但它在{print" 7"}之后挂起:

  

gzip:stdin:意外的文件结束   tar:存档中意外的EOF   tar:错误无法恢复:现在退出

因此,脚本不会继续执行下一个try语句。我的代码目前如下,任何建议都非常感谢。

try:
    with open(filename, 'wb') as file_to_write:
        print '1'

        def callback(chunk):
            print '2'
            file_to_write.write(chunk)
            print '3'
            if os.path.isfile(filename) and os.path.getsize(filename) > 400000:
                print os.path.getsize(filename), "FILE SIZE"
                subprocess.Popen(['tar', '-xvf', filename, '+CONTENTS'], stdout=subprocess.PIPE)
                print "4"
                try:
                    if os.path.isfile('+CONTENTS'):
                        last_size = []
                        content_size = os.path.getsize('+CONTENTS')
                        cnt_sz = content_size
                        last_size.append(cnt_sz)
                        print "5", last_size
                        print "6", cnt_sz
                        if max(last_size) == content_size:
                            print "7"
                            ftp.quit()
                except EnvironmentError:
                    pass
            else:
                print 'continuing'
                # time.sleep(.1)

        ftp.retrbinary("RETR %s" % filename, callback, 4096)
except EOFError, e:
    print e
    pass

1 个答案:

答案 0 :(得分:0)

所以我让它像这样工作,ftp.quit仍然导致我在这部分中的错误,所以我将在稍后的脚本中退出。

try:
    with open(filename, 'wb') as file_to_write:
        print '1'
        last_size = 0

        def callback(chunk):
            global last_size
            if last_size is None:
                last_size = 0
            print '2'
            file_to_write.write(chunk)
            print '3'
            if os.path.isfile(filename) and os.path.getsize(filename) > 400000:
                print os.path.getsize(filename), "FILE SIZE"
                subprocess.Popen(['tar', '-xvf', filename, '+CONTENTS'], stdout=subprocess.PIPE)
                print "4"
                try:
                    if os.path.isfile('+CONTENTS'):
                        content_size = os.path.getsize('+CONTENTS')
                        print "5", last_size
                        print "6", content_size
                        if last_size == content_size:
                            print "7"
                            raise Exception
                        last_size = content_size
                except EnvironmentError:
                    pass
            else:
                print 'continuing'

        ftp.retrbinary("RETR %s" % filename, callback, 4096)
except:
    pass