IntHeaderProtobufFile.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python
  2. #encoding:utf-8
  3. import string
  4. import struct
  5. from google.protobuf import message as _message
  6. class Reader(object):
  7. def __init__(self, protobufClass, file):
  8. self.protobufClass = protobufClass
  9. self.file = file
  10. self.f = open(self.file, "rb")
  11. closed = property(lambda self: self.f.closed)
  12. def __enter__(self):
  13. pass
  14. def __iter__(self):
  15. return self
  16. def next(self):
  17. header = self.f.read(4)
  18. if len(header) < 4:
  19. raise StopIteration()
  20. length = struct.unpack('>i', header)
  21. bytes = self.f.read(length[0])
  22. protoObj = self.protobufClass()
  23. protoObj.ParseFromString(bytes)
  24. return protoObj
  25. def __next__(self):
  26. self.next()
  27. def isclosed(self):
  28. return self.f.closed
  29. def close(self):
  30. self.f.close()
  31. def __exit__(self, exc_type, exc_val, exc_tb):
  32. if not self.closed:
  33. self.close()
  34. class Writer(object):
  35. def __init__(self, file):
  36. self.file = file
  37. self.f = open(self.file, "wb")
  38. closed = property(lambda self: self.f.closed)
  39. def __enter__(self):
  40. pass
  41. def write(self, message):
  42. if isinstance(message, str):
  43. length = len(message)
  44. self.f.write(struct.pack(">i", length))
  45. self.f.write(message)
  46. return
  47. if isinstance(message, _message.Message):
  48. bytes = message.SerializeToString()
  49. length = len(bytes)
  50. self.f.write(struct.pack(">i", length))
  51. self.f.write(bytes)
  52. return
  53. def flush(self):
  54. self.f.flush()
  55. def close(self):
  56. self.f.close()
  57. def isclosed(self):
  58. return self.f.closed
  59. def __exit__(self, exc_type, exc_val, exc_tb):
  60. if not self.closed:
  61. self.close()
  62. if __name__ == "__main__":
  63. pass