dumper.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. The dumper module provides functions to dump odML objects;
  3. Document, Section, Property; to the command line.
  4. """
  5. from .xmlparser import to_csv
  6. def get_props(obj, props):
  7. """
  8. Retrieves the values of a list of provided properties
  9. from an object and returns all values as a concatenated string.
  10. :param obj: odml object from which to retrieve specific property values.
  11. :param props: list of properties
  12. :returns: the obj property values as a concatenated string
  13. """
  14. out = []
  15. for prop in props:
  16. if hasattr(obj, prop):
  17. curr = getattr(obj, prop)
  18. if curr is not None:
  19. if isinstance(curr, (list, tuple)):
  20. out.append("%s=%s" % (prop, to_csv(curr)))
  21. else:
  22. out.append("%s=%s" % (prop, repr(curr)))
  23. return ", ".join(out)
  24. def dump_property(prop, indent=1):
  25. """
  26. Prints the content of an odml.Property.
  27. :param prop: odml.Property
  28. :param indent: number of prepended whitespaces. Default is 1.
  29. """
  30. prop_list = ["definition", "values", "uncertainty", "unit", "dtype",
  31. "value_reference", "dependency", "dependencyValue"]
  32. prop_string = get_props(prop, prop_list)
  33. print("%*s:%s (%s)" % (indent, " ", prop.name, prop_string))
  34. def dump_section(section, indent=1):
  35. """
  36. Prints the content of an odml.Section including any subsections
  37. and odml.Properties.
  38. :param section: odml.Section
  39. :param indent: number of prepended whitespaces. Default is 1.
  40. """
  41. if section is None:
  42. return
  43. prop_list = ["type", "definition", "link", "include", "repository"]
  44. prop_string = get_props(section, prop_list)
  45. print("%*s*%s (%s)" % (indent, " ", section.name, prop_string))
  46. for prop in section.properties:
  47. dump_property(prop, indent + 1)
  48. for sub in section.sections:
  49. dump_section(sub, indent * 2)
  50. def dump_doc(doc):
  51. """
  52. Prints the content of an odml.Document including any subsections
  53. and odml.Properties.
  54. :param doc: odml.Section
  55. """
  56. for sec in doc:
  57. dump_section(sec)