2016-11-10 44 views
0

我正在處理一個程序,該程序讀取日誌錯誤文件並從命令行參數中獲取文件,然後我必須打印大多數重複的25個錯誤。python3 for循環不能與urlopen一起工作

例如; (這是一個非常大的文件,所以我只是複製粘貼&幾行,以明確這一點)

[Sun Oct 09 14:15:52 2011] [error] [client 64.15.156.151] script '**/var/www/html/myip.php**' not found or unable to stat 

[Sun Oct 09 14:16:25 2011] [error] [client 64.15.156.151] script '**/var/www/html/myip.php**' not found or unable to stat 

[Sun Oct 09 14:18:42 2011] [error] [client 123.166.54.36] File does not exist: **/var/www/html/deny2** 

[Sun Oct 09 14:26:48 2011] [error] [client 66.249.68.178] File does not exist: **/home/ms10694/public_html/homepage/Midterm Project/zengarden-sample.html** 

[Sun Oct 09 14:29:59 2011] [error] [client 64.15.156.151] script '**/var/www/html/myip.php**' not found or unable to stat 

[Sun Oct 09 14:30:23 2011] [error] [client 38.99.97.53] File does not exist: /var/www/html/robots.txt** 

[Sun Oct 09 14:30:23 2011] [error] [client 38.99.97.53] File does not exist: **/var/www/html/favicon.ico** 

我需要尋找那些循環粗體地址,找到最重複的25個錯誤。

我的代碼搜索任何行包含'/var.....+',但由於某些原因,它確實在打印日誌錯誤文件時只是首先打印'/var...+'。 我在這裏錯過了什麼?

#!/usr/bin/env python3 
import urllib.request 
import re 
import sys 
import os 

Argument = sys.argv[1] 

LogErrorFile = urllib.request.urlopen(Argument) 

InBytes = LogErrorFile.read() 

InString = InBytes.decode("utf8") 

#for s in InString: 
text = InString 
for s in InString: 
FindLines = re.findall('/var.+', text) 
print (FindLines[0]) 

回答

0

有很多事情在這裏,所以我就給你一個稍微簡化版本,你在找什麼:

import io 
import re 
from sys import argv 

in_file = argv[1] 

with io.open(in_file, 'r', encoding='utf-8') as my_file: 
    for line in my_file: 
    print(re.findall('\/var.*', line)) 

爲什麼它保持打印第一/ VAR線?

因爲你要求它與零這裏:

FindLines[0] 

你如何定義「錯誤」(整條生產線只是一塊?)所以我不拉目前尚不清楚最常見的錯誤。並且該類型的錯誤文件通常不會被遠程檢索,所以我沒有包含urllib。相反,我認爲它是本地的,並使用io模塊。

希望有幫助!

+0

謝謝! 我不得不使用urllib,所以我這樣去了; 我把錯誤信息發送到dir中,所以我可以在那裏比較一下,我也在dic作品上設置了for循環,看起來應該如何。 – denizburak54