开发者

Python - Filter by Date

How do I count how many logins were do开发者_如何学Gone per day on a system using the log file in Python?


You don't need Python, the shell will do:

grep "Login succeeded_or_whatever_the_log_says" logfile | wc -l

If you really insist on using Python, try

print(sum(
     1 for line in open('logfile')
           if 'Login succeeded_or_whatever_the_log_says' in line))

If the login suceeded message spans multiple lines:

print(open('logfile').read().count('login\nsucceeded'))

You don't need to worry about closing the file handle; Python does that automatically when GCing a file handle:

$ touch x
$ python -c 'import time; open("x"); time.sleep(2)' & sleep 1 && fuser x
[1] 23232
$

but

$ python -c 'import time; f=open("x"); time.sleep(2)' & sleep 1 && fuser x
[1] 23265
x:                   23265
$


You can create dictionary with day as a key, and login count as a value. Then read file line by line, extract date from each line and increase login count for that day.

I think something like this should work:

login_cnts = {}

def get_date(line):
    """extract date from line, in this example line starts with YYYY-MM-DD (10 chars)"""
    if line and len(line) > 10:
        return line[:10]
    return None


for line in open(fname):
    date_str = get_date(line)
    if date_str:
        try:
            login_cnts[date_str] += 1
        except KeyError:
            login_cnts[date_str] = 1

days = login_cnts.keys()
days.sort()
for d in days:
    print("%s: %d" % (d, login_cnts[d]))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜