【问题标题】:Ignoring error raise while iterating through files with python使用python迭代文件时忽略错误引发
【发布时间】:2014-05-28 13:07:03
【问题描述】:

我目前正在执行一项任务,我需要使用 pefile 模块迭代多个可执行文件,代码如下所示

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

我使用 try 和 except 的目的是为了克服错误引发,只要可执行文件引发错误,其中 NT 标头给出无效签名,因为如果我不使用 try 和 except,代码将停止在它发现可执行文件无效的点NT 头签名

这就是我不使用 try 和 except 时消息的样子

PEFormatError: 'Invalid NT Headers signature.' 

但是使用上面的代码会导致死循环,请问有什么办法可以解决吗?

【问题讨论】:

  • 那么不要使用无限循环吗?将您的 try closer 移至异常;仅将其放在 pefile.PE() 调用周围。
  • @TheGameDoctor 请注意,您的字符串'C:\Documents and Settings\Zha\Desktop\PE benign\*.exe' 错误,如` is escape character. Correct it to 'C:\\Documents and Settings\\Zha\\Desktop\\PE 良性\*.exe'` 或到r'C:\Documents and Settings\Zha\Desktop\PE benign\*.exe' 或使用正斜杠'C:/Documents and Settings/Zha/Desktop/PE benign/*.exe'

标签: python python-2.7 exception exception-handling infinite-loop


【解决方案1】:

不要使用while True 循环。只需将try except 移动到for 循环中:

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)

此外,您的字符串格式化语法并没有错,但是,format 是格式化字符串的首选方式。

【讨论】:

  • 感谢这很有帮助,只是对除了 pefile.PEFormatError 以外的部分进行了一些更正。但总的来说,这非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2021-03-25
  • 2014-06-26
  • 2012-08-26
  • 2017-08-12
相关资源
最近更新 更多