Ignorando el aumento de error al iterar a través de archivos con python

I'm currently working on a task where I need to iterate multiple executable file using pefile module the code is look like this

while True:
    try:
        for filename in glob.iglob('C:\Documents and Settings\Zha\Desktop\PE benign\*.exe'):
            pe =  pefile.PE(filename)

            print '%x' % pe.FILE_HEADER.NumberOfSections

    except:
        pass

My intention using try and except is to overcome error raise whenever an executable that raising an error where NT header gives Invalid signature because if I do not use try and except the code will stop at the point where it found an executable with invalid NT header signature

this is what the message looks like if I don't use try and except

PEFormatError: 'Invalid NT Headers signature.' 

However using the code above will cause an infinite loop, is there any possible way to solve this?

preguntado el 28 de mayo de 14 a las 14:05

Don't use an infinite loop then? Move your try más cerca to the exception; put it around the pefile.PE() call only. -

@TheGameDoctor Mind, that your string 'C:\Documents and Settings\Zha\Desktop\PE benign\*.exe' está mal, como ` is escape character. Correct it to 'C:\\Documents and Settings\\Zha\\Desktop\\PE benign\*.exe'` or to r'C:\Documents and Settings\Zha\Desktop\PE benign\*.exe' or use forward slashes 'C:/Documents and Settings/Zha/Desktop/PE benign/*.exe' -

1 Respuestas

No use el while True loop. Simply move the try except en el for bucle:

for filename in glob.iglob('...'):
    try:
        pe = pefile.PE(filename)
    except PEFormatError as err:
        print "{} in file '{}'".format(err, filename)
        continue

    print '{}'.format(pe.FILE_HEADER.NumberOfSections)

Also, your string formatting syntax isn't wrong, however, format is the preferred way to format strings.

contestado el 28 de mayo de 14 a las 14:05

thanks this is helpful, just a little correction on part where except pefile.PEFormatError as err. But in general this is great thanks - TheGameDoctor

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.