Ignorando el aumento de error al iterar a través de archivos con python
Frecuentes
Visto 642 equipos
2
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?
1 Respuestas
1
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 python python-2.7 exception infinite-loop or haz tu propia pregunta.
Don't use an infinite loop then? Move your
try
más cerca to the exception; put it around thepefile.PE()
call only. - Martijn PietersVer también ¿Por qué "excepto: pasar" es una mala práctica de programación? - Martijn Pieters
@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 tor'C:\Documents and Settings\Zha\Desktop\PE benign\*.exe'
or use forward slashes'C:/Documents and Settings/Zha/Desktop/PE benign/*.exe'
- Jan Vlcinsky