1

我正在第一次尝试 Python。

我需要遍历日志,解析日志条目,然后更新一个对象,其中包括日志中列出的机器的嵌套对象。

这就是我所拥有的:

import re
format_pat= re.compile( 
    r"(?P<host>(?:[\d\.]|[\da-fA-F:])+)\s" 
    r"(?P<identity>\S*)\s" 
    r"(?P<user>\S*)\s"
    r"\[(?P<time>.*?)\]\s"
    r'"(?P<request>.*?)"\s'
    r"(?P<status>\d+)\s"
    r"(?P<bytes>\S*)\s"
    r'"(?P<referer>.*?)"\s'
    r'"(?P<user_agent>.*?)"\s*' 
)

from json import JSONEncoder
class MyEncoder(JSONEncoder):
    def default(self, o):
      return o.__dict__ 

# JSON response object
class ResponseObject(object):
    def __init__(self, dict):
      self.__dict__ = dict


# check for JSON response object
try:
    obj
except NameError:
    obj = ResponseObject({})

test = ['2001:470:1f14:169:15f3:824f:8a61:7b59 - SOFTINST [14/Nov/2012:09:32:31 +0100] "POST /setComputer HTTP/1.1" 200 4 "-" "-" 102356']

# log loop
for line in test:
  try:
    # try to create object from log entry
    m = format_pat.match(line)
    if m:
      res = m.groupdict()
      res["status"] = int(res["status"])

      # register machine if not done
      if not hasattr(obj, res["user"]):
        setattr(obj, res["user"], {"downtime":"0","flag":"false","downstart":"0","init":res["time"],"last":"","uptime":"","downtime":"","totaltime":""})


      machine = getattr(obj, res["user"])
      flag = machine["flag"]
      start = machine["downstart"]
      down = machine["downtime"]
      last = machine["last"]

      print "done"
      # set last
      last = res["time"]

      # PROBLEM this does not work
      setattr(machine, last, res["time"])
      print machine

    else:
      print "nope"
  except:
      print "nope base"

print MyEncoder().encode(obj)

我在尝试时遇到的错误setattr()

AttributeError: 'dict' object has no attribute ''

但我怕事情没有这么简单……

问题:
如何last使用“setattr”更新嵌套对象中的值?还是有另一种更新嵌套对象属性的方法?

4

3 回答 3

1

我认为你需要这样做:

setattr(machine, 'last', res["time"])

由于setattr需要一串要设置的属性名称

于 2013-03-05T16:21:31.360 回答
1

不要使用setattr. 只需"last"为每个machine字典的键分配一个值。

(实际上你回答了你自己的问题!)

于 2013-03-05T17:13:26.823 回答
0

I don't understand why, but I can set the value of last like this:

  print machine
  print machine["last"]
  print res["time"]

  # this works
  machine["last"] = res["time"]

  print machine

If someone can explain, would be nice :-)

于 2013-03-05T16:39:07.320 回答