python3 for循环不适用于urlopen

时间:2016-11-10 03:07:56

标签: python bash python-3.x unix

我正在努力研究一个读取日志错误文件并从命令行参数获取文件的程序,然后我必须打印大多数重复的25个错误。

例如; (这是一个非常大的文件,因此我只需复制并粘贴几行以使其清晰)

[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])

1 个答案:

答案 0 :(得分:0)

这里有很多事情发生,所以我会给你一个稍微简化的版本,你会发现:&/ p>

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模块。

希望有所帮助!