尝试除了传递函数不继续

Try except pass function not continuing

所以我需要帮助来传递我的异常并继续我的脚本的其余部分。简短的背景故事是我需要在 ftp 服务器上获取文件的前 400kb,其中包含我需要的 +CONTENTS 文件夹。我预计会出现文件结尾丢失的错误,因为我在文件完成之前终止了 ftp 连接。在我的测试中,我可以终止 ftp 连接,但它在 {print "7"} 说:

后挂起

gzip: stdin: unexpected end of file tar: Unexpected EOF in archive tar: Error is not recoverable: exiting now

因此,脚本不会继续执行下一个 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

所以我让它像这样工作,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