简体   繁体   English

python过滤器无法输出

[英]python filter can't output

i create filter by python to the log file like 我通过python创建过滤器到日志文件

    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

the script is 脚本是

import time
f= open("/opt/CLiMB/Storage1/log/vsftp.log")
def OnlyRecent(line):
    if  time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y") < time.time()-(60*60*24*2):
       return True
    return False

for line in f:
      if OnlyRecent(line):
         print line

f.close()

but when i run this script, it didn't show anything. 但是当我运行此脚本时,它什么也没显示。 Why it can't shows records happened in 2 days. 为什么它不能显示记录在两天内发生。 And Since the log file is very large, and records are sorted by time, so how to speed up to find records. 而且由于日志文件非常大,并且记录是按时间排序的,因此如何加快查找记录的速度。

Thanks 谢谢

This script won't print anything until it has fully processed the entire file in memory because of the final join. 由于最终的连接,该脚本在完全处理完内存中的整个文件之前不会打印任何内容。

If you want to print as it goes, use a loop and print for each line returned by the filter. 如果要按需打印,请使用循环并为过滤器返回的每一行打印。

import time
f = open("/opt/CLiMB/Storage1/log/vsftp.log")
f.readline() # Not sure why you're doing this, but retained to replicate behaviour

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

for line in f:
    if OnlyRecent(line):
        print line

f.close()

You are comparing two different data structures. 您正在比较两个不同的数据结构。 time.strptime() returns a struct time. time.strptime()返回一个结构时间。 Whereas, time.time() gives time in seconds since epoch. 而time.time()则以秒为单位,以秒为单位。

You can use the time.gmtime function to convert time since epoch to a time structure and then compare or use calendar.gmtime to convert struct time to time since epoch and then compare. 您可以使用time.gmtime函数将自纪元以来的时间转换为时间结构,然后进行比较,或使用calendar.gmtime将结构时间至纪元以来的时间转换,然后进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM