listing10-8.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # database.py
  2. import sys, shelve
  3. def store_person(db):
  4. """
  5. Query user for data and store it in the shelf object
  6. """
  7. pid = input('Enter unique ID number: ')
  8. person = {}
  9. person['name'] = input('Enter name: ')
  10. person['age'] = input('Enter age: ')
  11. person['phone'] = input('Enter phone number: ')
  12. db[pid] = person
  13. def lookup_person(db):
  14. """
  15. Query user for ID and desired field, and fetch the corresponding data from
  16. the shelf object
  17. """
  18. pid = input('Enter ID number: ')
  19. field = input('What would you like to know? (name, age, phone) ')
  20. field = field.strip().lower()
  21. print(field.capitalize() + ':', db[pid][field])
  22. def print_help():
  23. print('The available commands are:')
  24. print('store : Stores information about a person')
  25. print('lookup : Looks up a person from ID number')
  26. print('quit : Save changes and exit')
  27. print('? : Prints this message')
  28. def enter_command():
  29. cmd = input('Enter command (? for help): ')
  30. cmd = cmd.strip().lower()
  31. return cmd
  32. def main():
  33. database = shelve.open('C:\\database.dat') # You may want to change this name
  34. try:
  35. while True:
  36. cmd = enter_command()
  37. if cmd == 'store':
  38. store_person(database)
  39. elif cmd == 'lookup':
  40. lookup_person(database)
  41. elif cmd == '?':
  42. print_help()
  43. elif cmd == 'quit':
  44. return
  45. finally:
  46. database.close()
  47. if name == '__main__': main()