簡體   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