2010-03-20 133 views
-4

如何计算每天在使用Python中的日志文件的系统上完成多少次登录?Python - 按日期筛选

+0

相关:http://stackoverflow.com/questions/2483421/python-retrieving-info-from-a-syslog-file – sth 2010-03-20 16:35:58

+4

你有什么示例代码到目前为止?你试过的任何东西?任何我们可以评论的东西? – 2010-03-20 16:45:11

+0

不仅是重复的问题,而且是重复的帐户?这[小猪] [1]写了一个问题,这[小猪] [2]写了同样的问题,这两个小猪名为约翰尼... [1]:http://stackoverflow.com/users/298077/johnny [2]:http://stackoverflow.com/users/298037/johnny – Kiril 2010-03-20 19:16:40

回答

1

你不需要的Python,shell将做:

grep "Login succeeded_or_whatever_the_log_says" logfile | wc -l 

如果你真的坚持使用Python,尝试

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

如果登录suceeded消息跨越多行:

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

您不必担心关闭文件句柄; Python做自动GCing文件句柄时:

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

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

如果可能的话,千万不要在没有上下文管理器的情况下使用'open'('open('logfile')'作为f:')。特别是从来没有像这样使用它,你永远不会以某种方式调用'close'。 – 2010-03-20 16:59:56

+0

如果'Login succeeded_or_whatever_the_log_says'in line' – 2010-03-20 17:01:11

+0

@Mike Graham:你能解释一下风险吗?在这种情况下,我认为这很好,因为它是一个小程序。程序退出时,所有文件句柄都会关闭,不是吗?在我看来,最多只会抛出一个IOError异常......对于一个永远不会再被使用的简短脚本来说这不算太坏。 – 2010-03-20 17:22:53

-1

您可以创建日辞典作为重点,并登录计数的值。 然后逐行读取文件,从每行提取日期并增加当天的登录次数。

我觉得这样的事情应该工作:

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

不要在没有上下文管理器的情况下使用'open'。 – 2010-03-20 17:01:38

+0

不要使用'None'之类的返回值来指示失败。使用例外。 – 2010-03-20 17:02:21

+0

它看起来像你想'login_cnts = collections.defaultdict(int)'。这将简化'try:login_cnts [date_str] + = 1,除了KeyError:login_cnts [date_str] = 1'到'login_cnts [date_str] + = 1'。由于遇到这种类型的问题,“setdefault”方法和“collections.defaultdict”被添加到Python中。 – 2010-03-20 17:04:03