Introduce old redir program
[lcapit-junk-code.git] / CEP / cep-browser.py
blobe1d637cbff0da9b01dcb36f119b2d3fd3b19746f
1 #!/usr/bin/python
3 # Python version of the CEP browser program
5 # Note: dict type in python is implemented using a hash
6 # table.
8 # Luiz Fernando N. Capitulino
9 # <lcapitulino@gmail.com>
11 import sys
13 class Address:
14 def dump(self):
15 print '%s;%s;%s;%s;%s' % \
16 (self.__cep, self.__uf, self.__cidade, \
17 self.__bairro, self.__rua)
19 def get_cep(self):
20 return self.__cep
22 def __cmp__(self, y):
23 return self.__cep == y;
25 def __repr__(self):
26 str = '\n'
27 str += 'CEP: ' + self.cep + '\n'
28 str += 'UF: ' + self.uf + '\n'
29 str += 'Cidade: ' + self.cidade + '\n'
30 str += 'Bairro: ' + self.bairro + '\n'
31 str += 'Rua: ' + self.rua + '\n'
32 return str
34 def __init__(self, line):
35 items = line.split(";")
36 self.__rua = items.pop()
37 self.__bairro = items.pop()
38 self.__cidade = items.pop()
39 self.__uf = items.pop()
40 self.__cep = items.pop()
42 class AddressList(list):
43 def lookup(self, cep):
44 for entry in self:
45 if entry == cep:
46 return entry
47 return None
49 def __init__(self, contents):
50 list.__init__(self)
51 for line in contents:
52 addr = Address(line.strip('\n\r'))
53 self.append(addr)
55 class AddressDict(dict):
56 lookup = dict.get
58 def __init__(self, contents):
59 dict.__init__(self)
60 for line in contents:
61 addr = Address(line.strip('\n\r'))
62 self.setdefault(addr.get_cep(), addr)
64 def read_db(dbpath):
65 db = open(dbpath)
66 contents = db.readlines()
67 db.close()
68 return contents
70 def do_test(addresses, contents):
71 failed = False
72 for line in contents:
73 cep = line[:line.find(';')]
74 ret = addresses.lookup(cep)
75 if ret is None:
76 failed = True
77 break
78 if failed:
79 print 'FAILED'
80 else:
81 print 'PASSED'
84 def shell(addresses):
85 while True:
86 sys.stdout.write('>>> ')
87 line = sys.stdin.readline()
89 if len(line) == 0:
90 print
91 return
93 if line == '\n':
94 continue
96 line = line.strip('\n')
97 entry = addresses.lookup(line)
98 if entry is not None:
99 print entry
100 else:
101 print line + ' : not found'
102 def usage():
103 print 'usage: cep-browser.py [ -l | -d ] [ -t ] < filename >'
104 sys.exit(1)
106 def main():
108 if len(sys.argv) < 3 or len(sys.argv) > 4:
109 usage()
111 opt = sys.argv[1]
112 if opt != "-l" and opt != "-d":
113 usage()
115 run_test = False
116 file = sys.argv[2]
118 if sys.argv[2] == "-t":
119 run_test = True
120 file = sys.argv[3]
122 contents = read_db(file)
124 if opt == "-l":
125 addresses = AddressList(contents)
126 else:
127 addresses = AddressDict(contents)
129 if run_test is True:
130 do_test(addresses, contents)
131 sys.exit(0)
133 shell(addresses)
135 if __name__ == "__main__":
136 main()