#coding = utf-8
#!/usr/bin/env python
import shelve
class MySheve:
cmd = {'Add':'AddData','Delete':'DeleteData','Modify':'ModifyData','Find':'FindByName',
'Show':'ShowData','Help':'Help'}
def __init__(self, fileName):
self.db = {}
self.key = 1
self.fileName = fileName;
def __OpenShelve(self):
self.db=shelve.open(self.fileName,'c')
def __CloseShelve(self):
self.db.close()
def AddData(self):
self.__OpenShelve()
person = {}
person['name'] = raw_input('Name: ')
person['sex']=raw_input('Sex: ')
person['age']=raw_input('age: ')
self.db[str(self.key)] = person
self.key += 1
self.__CloseShelve()
def FindByName(self):
self.__OpenShelve()
name = raw_input('Input who you want to find?>')
res = []
for key,value in self.db.iteritems():
if value['name'] == name:
res.append(key)
if not res:
print 'no this record'
self.__CloseShelve()
return res
def ModifyData(self):
keys = self.FindByName()
if not keys :
print 'not find record'
print 'find follow record'
self.__OpenShelve()
for key in keys:
print key,self.db[key]
key =raw_input('which record you will modify? >')
person = {}
person['name'] = raw_input('Name: ')
person['sex']=raw_input('Sex: ')
person['age']=raw_input('age: ')
self.db[key]=person
self.__CloseShelve()
def DeleteData(self):
keys = self.FindByName()
if not keys :
print 'not find record'
print 'find follow record'
self.__OpenShelve()
for key in keys:
print key,self.db[key]
key =raw_input('which record you will delete? >')
del self.db[key]
self.__CloseShelve()
return None
def ShowData(self):
self.__OpenShelve()
for key,value in self.db.iteritems():
print key,value
self.__CloseShelve()
def Help(self):
print 'this system have follow operation:'
print 'help you can which operation you can use and how to use'
print 'Add you can add a data to your database'
print 'Delete you can delete a data specified by name'
print 'Modify you can modify a data specified by name'
print 'Find you can find a data in your database'
print 'Exit Exit system'
def CmdProc(self):
while(True):
cmd_key = raw_input('cmd > ')
if cmd_key in self.cmd.keys():
method=getattr(self,self.cmd[cmd_key])
method()
else:
print 'cmd your input is invalid,please input again!'
if __name__ == '__main__':
db = MySheve('123')
db.CmdProc()
python 利用Shelve实现在命令行下的数据自动管理
最新推荐文章于 2020-12-21 10:23:14 发布