Using the tinycdb index files.
1
2
15
16import msparser
17import sys
18import re
19
20def main() :
21
22
23
24 version = "1.1"
25 sourceFile = sys.argv[0]
26 cdbname = sys.argv[0] + '.cdb'
27 cdb = msparser.ms_tinycdb(cdbname, version, sourceFile)
28
29 if not cdb.isValid() :
30 showErrors(cdb)
31 return 1
32
33 if not cdb.openIndexFile(True) :
34 if cdb.isPossibleToCreate() :
35 print("Creating file because: %s" % cdb.getLastErrorString())
36 cdb.prepareToCreate()
37 cdb.saveValueForKey("Hello", "world")
38
39
40 cdb.saveValueForKey("HELP", "me")
41 cdb.saveValueForKey("HELP", "me too")
42
43
44
45
46
47
48 try :
49 fh = open(sys.argv[0], 'r')
50 except IOError as err:
51 errno, strerror = err.args
52 print("Cannot open " + sys.argv[0] + " for reading: " + strerror)
53 return 1
54 sys.exit(1)
55 line_nr = 1
56 for line in fh :
57 if re.search('\s*# and saves an.*', line) :
58 break
59
60 line_nr += 1
61
62 fh.close();
63
64 cdb.saveIntForKey("Line", line_nr)
65 cdb.finishCreate()
66
67
68 if cdb.isValid() :
69 print("Retrieving value for Hello : %s" % cdb.getValueFromKey("Hello"))
70 print("Retrieving 1st value for HELP : %s" % cdb.getValueFromKey("HELP", 0))
71 print("Retrieving 2nd value for HELP : %s" % cdb.getValueFromKey("HELP", 1))
72
73
74 try :
75 fh = open(sys.argv[0], 'r')
76 except IOError as err:
77 errno, strerror = err.args
78 print("Cannot open " + sys.argv[0] + " for reading: " + strerror)
79 return 1
80
81 line_nr = cdb.getIntFromKey("Line")
82
83 i = 1
84 for line in fh :
85 if i == line_nr : break
86 i += 1
87
88 print("Testing line index. Line " + str(line_nr + 1) + " : " + line)
89 fh.close()
90 else :
91 showErrors(cdb)
92
93
94def showErrors(obj) :
95 err = obj.getErrorHandler()
96
97 for i in range(1, 1 + err.getNumberOfErrors()) :
98 print("Error number: %d (%d times): %s" % (err.getErrorNumber(i), err.getErrorRepeats(i) + 1, err.getErrorString(i)))
99
100 print(" ")
101 obj.clearAllErrors()
102
103if __name__ == "__main__" :
104 sys.exit(main())
105