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?

  • 2
    Don't use an infinite loop then? Move your `try` *closer* to the exception; put it around the `pefile.PE()` call only. – Martijn Pieters May 28 '14 at 13:08
  • Also see [Why is "except: pass" a bad programming practice?](http://stackoverflow.com/q/21553327) – Martijn Pieters May 28 '14 at 13:08
  • @TheGameDoctor Mind, that your string `'C:\Documents and Settings\Zha\Desktop\PE benign\*.exe'` is wrong, as `\` 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'` – Jan Vlcinsky May 28 '14 at 13:15

1 Answers1

1

Don't use the while True loop. Simply move the try except into the for loop:

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.

BeetDemGuise
  • 954
  • 7
  • 11
  • thanks this is helpful, just a little correction on part where except pefile.PEFormatError as err. But in general this is great thanks – TheGameDoctor May 29 '14 at 04:27