OC

Knowledge OS
登录 注册
全部话题 移民 创业 iOS Mac Objective-C Swift Android 招聘 求职

python小白,求救贴。请大神指导一下

willmars
willmars 发布于 2015年12月05日 | 更新于 2015年12月11日
无人欣赏。

这是错误

 self.assertFalse(ipValues[iNum],valueList2[iNum],"The result of sorti
TypeError: 'NoneType' object is unsubscriptable

源码: 文件名:logtest.py

#!/usr/bin/python 
def countIP(file):
 ipCounter = {}
 testF = open(file,"r+")
 for line in testF.readlines():
 if '[client ' in line:
 ip = line.split('[client ')[1].split(']')[0]
 ipCounter[ip] = ipCounter.get(ip,0)+1
 ipCounter = sorted(ipCounter.iteritems(), key = lambda d:d[1], reverse=True)
 print (ipCounter)
 testF.close()
 return ipCounter

单测代码 test_logtest.py

import unittest
import logtest
class TestCase(unittest.TestCase):
def testother_file_test(self):
 """check mail_log in different text"""
 self.assertTrue(logtest.countIP("error_log.2015年11月18日-18"))
def testvalue_test(self):
 """check ip`s value is sorted or not"""
 ipVList = {}
 ipValues = []
 ipVList = logtest.countIP("error_log.2015年11月18日-18")
 for l in ipVList:
 ipValue = l[1]
 ipValues.append(ipValue)
 valueList2 = []
 valueList2 = ipValues.sort(reverse = True) 
 if not ipValues:
 for iNum in range(len(ipValues)):
 self.assertFalse(ipValues[iNum],valueList2[iNum],"The result of sorting is wrong")
 if __name__ == '__main__':
 unittest.main()
共12条回复
楼长 ·
tinyfool 回复于 2015年12月05日

你是从哪里抄的代码么?抄的时候抄对了么?

2楼 ·
willmars 回复于 2015年12月05日

1楼 @tinyfool 我自己写的啊。复制贴过来的

3楼 ·
tinyfool 回复于 2015年12月05日

那这句

AttributeError: 'module' object has no attribute 'ipCounter'

看不懂么?

4楼 ·
willmars 回复于 2015年12月05日

3楼 @tinyfool 模块里没有ipCounter。可是不知道怎么改

5楼 ·
cnsoft 回复于 2015年12月05日

4楼 @willmars 是不是 error_log.2015年11月18日-18 个文件找不到. 你把文件和py放在一个目录下 再run试试

6楼 ·
tinyfool 回复于 2015年12月05日

4楼 @willmars 我不建议你一开始就写这么长,在初学阶段,代码可以一行一行的写,每一行都运行,这样你就知道加了什么东西,造成问题了,而不是先写了几十行,然后,才第一次执行,出了问题就很难理解了

7楼 ·
iamshok 回复于 2015年12月08日

迭代写呗,从能跑起来的代码开始。PS:ipCounter总感觉像是自己写的一个模块把

8楼 ·
loadatom1 回复于 2015年12月09日

这句错了 valueList2 = ipValues.sort(reverse = True)
list.sort返回的是None,

其实这个很好查。。错误说的是assert里面对None[idx],那么assert总共就2个[],分别是ipValues和valueList2。然后向上看两个变量的赋值。

ipValues = [],后面就一直是对这个列表变更。所以ipValues是好的。

而valueList2 = ipValues.sort(reverse = True) ,这一句那要看sort会返回什么值,这时不管查文档,还是在idle写两行代码测试,都能发现sort没返回值得。。

或者在assert前print这两个变量,也能发现问题

9楼 ·
biiigfish 回复于 2015年12月09日

照着敲,改改看,自己写。。。三步走,是最快的办法。

10楼 ·
biiigfish 回复于 2015年12月09日

使用你的代码(我自己敲,调试找完了bug),然后用下面的log文件,测试正常:

[client 192.168.1.230]
[client 192.168.1.222]

结果:

$ python test.logtest.py 
192.168.1.230
192.168.1.222
[('192.168.1.230', 1), ('192.168.1.222', 1)]
.192.168.1.230
192.168.1.222
[('192.168.1.230', 1), ('192.168.1.222', 1)]
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
本帖有12个回复,因为您没有注册或者登录本站,所以只能看到本帖的10条回复。如果想看到全部回复,请注册或者登录本站。
登录 或者 注册
[顶 楼]
|
|
[底 楼]
|
|
[首 页]

AltStyle によって変換されたページ (->オリジナル) /