尝试除了没有从类中捕获IOError

时间:2013-01-19 18:35:22

标签: python exception try-catch

我有一个类,它读取特定格式的文件。这些文件的大小往往大于8Gb,因此通常会被压缩。在读取文件时,我想捕获文件未被压缩的错误,但except IOError:except:都不会这样做,出于某种原因,我不明白。

文件 VCF.py 中一起定义了几个类,但有问题的类是vcfReader()。实例化对象的文件位于 test.py 之下,最后是Traceback。

任何人都有任何想法,为什么它不起作用?

VCF.py

import gzip
import sys

class Call():
    '''
    Class to handle the sample genotypes and associated information
    '''

    def __init__(self,site,sample,format,data):
        #do stuff here#

class Variant():
    '''
    Class for a single row from a VCF file.
    '''
    def __init__(self, entry, samples):
       #do other stuff here


class vcfReader():
    '''
    read a compressed vcf file ignoring the meta-information, but parsing the header             for sample names
    '''  
    def __init__(self, file):
        try:
            self.vcfFile = gzip.open(file, 'rb')
        except IOError:
            print "Not a gzipped file"
            sys.exit()

        self.samples = self.readHeader()

    def readHeader(self):
        line = self.vcfFile.next()
        while line.startswith('#'):
            if line[1]!='#':
                #lines that start with ##, i.e. meta tags are ignored. Header line starting with '#', sample names are extracted.
                return line.rstrip().rsplit('\t')[9:]
            else:           
                line = self.vcfFile.next()

    def __iter__(self):
        return self

    def next(self):
        row =  self.vcfFile.next()
        return Variant(row, self.samples)

然后 test.py

import VCF
from collections import Counter

if __name__=='__main__':
    vcfreader = VCF.vcfReader('all_samples.vcf')

    filters = []
    for i in vcfreader:
        filters.extend(i.FILTERS)

    filters = Counter(filters)

    for k,v in filters.iteritems():
        print "{0}: {1}".format(k,v)

这是追溯:

Traceback (most recent call last):
  File "C:\Users\Davy\Documents\Programming\VCF_stuff\src\test.py", line 10, in <module>
    vcfreader = VCF.vcfReader('all_samples.vcf')
  File "C:\Users\Davy\Documents\Programming\VCF_stuff\src\VCF.py", line 95, in __init__
    self.samples = self.readHeader()
  File "C:\Users\Davy\Documents\Programming\VCF_stuff\src\VCF.py", line 98, in readHeader
    line = self.vcfFile.next()
  File "C:\Python27\lib\gzip.py", line 450, in readline
    c = self.read(readsize)
  File "C:\Python27\lib\gzip.py", line 256, in read
    self._read(readsize)
  File "C:\Python27\lib\gzip.py", line 291, in _read
    self._read_gzip_header()
  File "C:\Python27\lib\gzip.py", line 185, in _read_gzip_header
    raise IOError, 'Not a gzipped file'
IOError: Not a gzipped file

1 个答案:

答案 0 :(得分:4)

except阻止未捕获异常的原因是它发生在try块之外:

def __init__(self, file):
    try:
        self.vcfFile = gzip.open(file, 'rb')
    except IOError:
        print "Not a gzipped file"
        sys.exit()

    self.samples = self.readHeader() # <<<<<<<< exception is raised here