2012-09-10 16 views
-3

我開始學習python,但遇到了SyntaxError。當我建立篩選器以獲取日誌文件中的最新記錄時。這樣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 "[email protected]" 
    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 

如何解決它。謝謝!

回答

1

以前的答案是正確的,但是自從您使用Python版本3.x +以來,還有另一個語法錯誤,其中print始終被稱爲函數。

因此,添加額外的paren,然後讓你的print調用一個函數調用。

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

P.S.使用變量而不是將大量工作放在一行 中以使代碼更具可讀性也是一個好主意。

+0

謝謝,當我改變它,它有新的錯誤。我已經編輯問題。 – AntiGMO

+1

@JesseSiu:額外的括號被添加在錯誤的地方。你需要在格式化字符串後加上它,例如'time.strptime(line.split(「[」)[0] .strip(),「%a%b%d%H:%M:%S%Y」 )<(time.time() - (60 * 60 * 24 * 5))'。該錯誤消息是由於您將字符串與作爲bool的浮點數作爲「strptime」的第二個參數進行比較的結果傳遞而導致的。另外,由於它看起來像使用Python 2.4,因此在'print'周圍添加括號不應該改變任何內容,所以你所說的話不可能是正確的。 – DSM

+0

@DSM:謝謝,你能給我更多的細節,如何解決它 – AntiGMO

0

在這條線上return time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y" <(time.time()-(60*60*24*5))你有一個缺少右括號')'。

0

您需要在return語句結尾處附加一個附加的paranthesis。

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

你可以從你的控制檯本身找到這個!

+0

後,我加入「)」,它仍然有同樣的問題 – AntiGMO

+0

這是不對的。它將修正不平衡括號可能導致的SyntaxError,但它引入了一個TypeError,因爲'strptime'應該只有兩個參數,第二個參數應該是格式,而不是'str'與'float'的比較結果。 – DSM

+0

上述問題並不具有建設性。我們不是在這裏解決語法錯誤。這是我的觀點。上面的代碼需要更多的清洗 –

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)