forked from lionsoul2014/ip2region
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testSearcher.py
83 lines (68 loc) · 2.24 KB
/
testSearcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#-*- coding:utf-8 -*-
"""
" ip2region python seacher client module
"
" Autho: koma<[email protected]>
" Date : 2015-11-06
"""
import struct, sys, os, time
from platform import python_version
from ip2Region import Ip2Region
def testSearch():
"""
" ip2region test function
"""
argLen = len(sys.argv)
version = python_version()
algorithms = ["binary", "b-tree", "memory"]
if argLen < 2:
print("Usage: python testSearcher.py [ip2region db file] [alrogrithm]")
print("Algorithm: %s" % ", ".join(algorithms))
return 0
dbFile = sys.argv[1]
if (not os.path.isfile(dbFile)) or (not os.path.exists(dbFile)):
print("[Error]: Specified db file is not exists.")
return 0
if argLen > 2:
algorithm = sys.argv[2]
try:
algorithms.index(algorithm)
except Exception as e:
algorithm = "b-tree"
print("initializing %s..." % (algorithm))
print("+----------------------------------+")
print("| ip2region test program |")
print("| Author: [email protected]. |")
print("| Type 'quit' to exit program |")
print("+----------------------------------+")
searcher = Ip2Region(dbFile)
while True:
if version[:1] == "2":
line = raw_input("ip2region>> ")
else:
line = input("ip2region>> ")
line = line.strip()
if line == "":
print("[Error]: Invalid ip address.")
continue
if line == "quit":
print("[Info]: Thanks for your use, Bye.")
break
if not searcher.isip(line):
print("[Error]: Invalid ip address.")
continue
try:
sTime = time.time()*1000
if algorithm == "binary":
data = searcher.binarySearch(line)
elif algorithm == "memory":
data = searcher.memorySearch(line)
else:
data = searcher.btreeSearch(line)
eTime = time.time()*1000
print("%s|%s in %5f millseconds" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
except Exception as e:
print("[Error]: %s" % e)
searcher.close()
if __name__ == "__main__":
testSearch()