You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

serialize.py 1.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """The functions in this file is used to dump and load python object in anf graphs."""
  16. import pickle
  17. import os
  18. import stat
  19. def dump_obj(obj, path):
  20. """Dump object to file."""
  21. file_name = hex(id(obj))
  22. file_path = path + file_name
  23. with open(file_path, 'wb') as f:
  24. os.chmod(file_path, stat.S_IWUSR | stat.S_IRUSR)
  25. pickle.dump(obj, f)
  26. return file_name
  27. def load_obj(file_path):
  28. """Load object from file."""
  29. obj = None
  30. try:
  31. real_file_path = os.path.realpath(file_path)
  32. except Exception as ex:
  33. raise RuntimeError(ex)
  34. with open(real_file_path, 'rb') as f:
  35. obj = pickle.load(f)
  36. return obj
  37. __all__ = ['dump_obj', 'load_obj']