繁体   English   中英

多处理未捕获异常

[英]Exception not caught in multiprocessing

我正在使用多处理模块并行处理文件,几乎每次都能很好地工作。 另外,我在try中编写了代码,除了block可以捕获任何异常。 我遇到了一种情况,其中except块无法捕获异常。

由于代码巨大,因此我只放置了相关的代码块,这给了问题。

  def reader(que, ip, start, end, filename):
  """ Reader function checks each line of the file
  and if the line contains any of the ip addresses which are
  being scanned, then it writes to its buffer.
  If the line field doesn't match date string it skips the line.
  """

  logging.info("Processing :   %s" % os.path.basename(filename))
  ip_pat = re.compile("(\d+\.\d+\.\d+\.\d+\:\d+)")
  chunk = 10000000 # taking chunk of 10MB data

  buff = ""
  with bz2.BZ2File(filename,"rb", chunk) as fh: # open the compressed file
      for line in fh:
          output = []
          fields = line.split()
          try:
              ts = fields[1].strip() + "/" +fields[0]+"/"+fields[3].split("-")[0]+" "+fields[2]
              times = da.datetime.strptime(ts,"%d/%b/%Y %H:%M:%S")
              if times < start:
                  continue
              if times > end:
                  break
              ips = re.findall(ip_pat,line)
              if len(ips) < 3:
                  continue
              if ips[0].split(":")[0] == ip:
                  output.append(times.strftime("%d/%m/%Y %H:%M:%S"))
                  status = "SESSION_OPEN" if "SESSION_OPEN" in line or "CREATE" in line else "SESSION_CLOSE"
                  protocol = "TCP" if "TCP" in line else "UDP"
                  output.append(status)
                  output.append(protocol)
                  ips[1], ips[2] = ips[2], ips[1]
                  output.extend(ips)
                  res = "|".join(output)
                  buff += res + "\n"
          except IndexError, ValueError:
              continue
  logging.info("Processed  :   %s of size [ %d ]" % (os.path.basename(filename), os.path.getsize(filename)))
  if buff:
    que.put((ip,buff))
  return buff

这就是错误。

文件“ /usr/lib64/python2.7/multiprocessing/pool.py”,第554行,在get throw self._value ValueError中:时间数据'2 / Dec / 20 10:59:59'与格式'%d不匹配/%b /%Y%H:%M:%S'

我不明白的是为什么未捕获异常,我在except块中提到了ValueError。

解决此问题的最佳方法是什么。

提供多个异常作为元组:

except (IndexError, ValueError):
          continue

相关文档为https://docs.python.org/2/tutorial/errors.html#handling-exceptions

页面摘录:

请注意,必须在该元组周围加上括号,因为在现代Python中,除ValueError之外,e:是通常用作除ValueError之外的e:的语法(如下所述)。 为了向后兼容,仍旧支持旧语法。 这意味着,除了RuntimeError之外,TypeError不等同于(RuntimeError,TypeError):但不等同于RuntimeError作为TypeError:,这不是您想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM