-3

我开始学习 python,但遇到了 SyntaxError。当我构建过滤器以获取日志文件中的最新记录时。像这样的日志文件

  Sat Jun  2 03:32:13 2012 [pid 12461] CONNECT: Client "66.249.68.236"
  Sat Jun  2 03:32:13 2012 [pid 12460] [ftp] OK LOGIN: Client "66.249.68.236", anon     password "gxxglxxxxt@google.com"
  Sat Jun  2 03:32:14 2012 [pid 12462] [ftp] OK DOWNLOAD: Client "66.249.68.236",   "/pub/10.5524/100001_101000/100022/readme.txt", 451 bytes, 1.39Kbyte/sec


import time
lines=[]
f= open("/opt/CLiMB/Storage1/log/vsftp.log")
line = f.readline()
lines=[line for line in f]
def OnlyRecent(line):
    return time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y" <(time.time()-(60*60*24*5)))
print ("\n".join(filter(OnlyRecent,lines)))
f.close()

运行时出错

 Traceback (most recent call last):
 File "ex2.py", line 8, in ?
 print("\n".join(filter(OnlyRecent,lines)))
 File "ex2.py", line 7, in OnlyRecent
 return time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y" <(time.time()-(60*60*24*5)))
 File "/usr/lib64/python2.4/_strptime.py", line 287, in strptime
 format_regex = time_re.compile(format)
 File "/usr/lib64/python2.4/_strptime.py", line 264, in compile
 return re_compile(self.pattern(format), IGNORECASE)
 File "/usr/lib64/python2.4/_strptime.py", line 251, in pattern
 format = regex_chars.sub(r"\\\1", format)
 TypeError: expected string or buffer

如何解决它。谢谢!

4

4 回答 4

1

前面的答案是正确的,但是由于您使用的是 python 版本 3.x+,因此还有另一个语法错误,其中print始终作为函数调用。

因此,添加额外的括号,然后,使您的print调用成为函数调用。

print("\n".join(filter(OnlyRecent,lines)))

PS 使用变量而不是将大量工作塞进一行以使您的代码更具可读性也是一个好主意。

于 2012-09-10T04:11:27.063 回答
0

在这一行return time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y" <(time.time()-(60*60*24*5))中,您缺少一个右括号')'。

于 2012-09-10T04:05:14.307 回答
0

您需要在 return 语句的末尾加上一个额外的右括号。

>>> def OnlyRecent(line):
...     return time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y"   <(time.time()-(60*60*24*5)))

您可以从控制台本身找到它!

于 2012-09-10T04:05:15.517 回答
0

通过保持简短的行使您的代码更易于阅读:

import time

def is_recent(line):
    time_string = line.split("[")[0].strip()
    line_time = time.strptime(time_string, '%a %b %d %H:%M:%S %Y')

    return line_time < (time.time() - (60 * 60 * 24 * 5))

with open('/opt/CLiMB/Storage1/log/vsftp.log', 'r') as handle:
    lines = filter(is_recent, handle)

print '\n'.join(lines)
于 2012-09-10T04:13:56.373 回答