trybag.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import pythoncom
  2. from win32com.server import util
  3. from win32com.server import exception
  4. VT_EMPTY = pythoncom.VT_EMPTY
  5. class Bag:
  6. _public_methods_ = [ 'Read', 'Write' ]
  7. _com_interfaces_ = [ pythoncom.IID_IPropertyBag ]
  8. def __init__(self):
  9. self.data = { }
  10. def Read(self, propName, varType, errorLog):
  11. print("read: name=", propName, "type=", varType)
  12. if propName not in self.data:
  13. if errorLog:
  14. hr = 0x80070057
  15. exc = pythoncom.com_error(0, "Bag.Read", "no such item", None, 0, hr)
  16. errorLog.AddError(propName, exc)
  17. raise exception.Exception(scode=hr)
  18. return self.data[propName]
  19. def Write(self, propName, value):
  20. print("write: name=", propName, "value=", value)
  21. self.data[propName] = value
  22. class Target:
  23. _public_methods_ = [ 'GetClassID', 'InitNew', 'Load', 'Save' ]
  24. _com_interfaces_ = [ pythoncom.IID_IPersist,
  25. pythoncom.IID_IPersistPropertyBag ]
  26. def GetClassID(self):
  27. raise exception.Exception(scode=0x80004005) # E_FAIL
  28. def InitNew(self):
  29. pass
  30. def Load(self, bag, log):
  31. print(bag.Read('prop1', VT_EMPTY, log))
  32. print(bag.Read('prop2', VT_EMPTY, log))
  33. try:
  34. print(bag.Read('prop3', VT_EMPTY, log))
  35. except exception.Exception:
  36. pass
  37. def Save(self, bag, clearDirty, saveAllProps):
  38. bag.Write('prop1', 'prop1.hello')
  39. bag.Write('prop2', 'prop2.there')
  40. class Log:
  41. _public_methods_ = [ 'AddError' ]
  42. _com_interfaces_ = [ pythoncom.IID_IErrorLog ]
  43. def AddError(self, propName, excepInfo):
  44. print("error: propName=", propName, "error=", excepInfo)
  45. def test():
  46. bag = Bag()
  47. target = Target()
  48. log = Log()
  49. target.Save(bag, 1, 1)
  50. target.Load(bag, log)
  51. comBag = util.wrap(bag, pythoncom.IID_IPropertyBag)
  52. comTarget = util.wrap(target, pythoncom.IID_IPersistPropertyBag)
  53. comLog = util.wrap(log, pythoncom.IID_IErrorLog)
  54. comTarget.Save(comBag, 1, 1)
  55. comTarget.Load(comBag, comLog)
  56. if __name__ == '__main__':
  57. test()