basics.py
Go to the documentation of this file.
1 import string
2 import yaml
3 import collections
4 
5 from xml.etree import ElementTree as ET
6 from xml.dom import minidom
7 
8 
9 def xml_string(rootXml, addHeader=True):
10  # From: https://stackoverflow.com/a/1206856/170413
11  # TODO(eacousineau): This does not preserve attribute order. Fix it.
12  dom = minidom.parseString(ET.tostring(rootXml))
13  xml_string = ""
14  lines = dom.toprettyxml(indent=" ").split("\n")
15  if lines and lines[0].startswith("<?xml") and not addHeader:
16  del lines[0]
17  # N.B. Minidom injects some pure-whitespace lines. Remove them.
18  return "\n".join(filter(lambda line: line.strip(), lines))
19 
20 
21 def dict_sub(obj, keys):
22  return dict((key, obj[key]) for key in keys)
23 
24 
25 def node_add(doc, sub):
26  if sub is None:
27  return None
28  if type(sub) == str:
29  return ET.SubElement(doc, sub)
30  elif isinstance(sub, ET.Element):
31  doc.append(sub) # This screws up the rest of the tree for prettyprint
32  return sub
33  else:
34  raise Exception('Invalid sub value')
35 
36 
37 def pfloat(x):
38  return str(x).rstrip('.')
39 
40 
41 def xml_children(node):
42  return list(node)
43 
44 
45 def isstring(obj):
46  try:
47  return isinstance(obj, basestring)
48  except NameError:
49  return isinstance(obj, str)
50 
51 
52 def to_yaml(obj):
53  """ Simplify yaml representation for pretty printing """
54  # Is there a better way to do this by adding a representation with
55  # yaml.Dumper?
56  # Ordered dict: http://pyyaml.org/ticket/29#comment:11
57  if obj is None or isstring(obj):
58  out = str(obj)
59  elif type(obj) in [int, float, bool]:
60  return obj
61  elif hasattr(obj, 'to_yaml'):
62  out = obj.to_yaml()
63  elif isinstance(obj, type(ET.Element)):
64  out = xml_string(obj, addHeader=False)
65  elif type(obj) == dict:
66  out = {}
67  for (var, value) in obj.items():
68  out[str(var)] = to_yaml(value)
69  elif hasattr(obj, 'tolist'):
70  # For numpy objects
71  out = to_yaml(obj.tolist())
72  elif isinstance(obj, collections.Iterable):
73  out = [to_yaml(item) for item in obj]
74  else:
75  out = str(obj)
76  return out
77 
78 
79 class SelectiveReflection(object):
80  def get_refl_vars(self):
81  return list(vars(self).keys())
82 
83 
85  def to_yaml(self):
86  raw = dict((var, getattr(self, var)) for var in self.get_refl_vars())
87  return to_yaml(raw)
88 
89  def __str__(self):
90  # Good idea? Will it remove other important things?
91  return yaml.dump(self.to_yaml()).rstrip()
def xml_string(rootXml, addHeader=True)
Definition: basics.py:9


urdfdom_py
Author(s): Thomas Moulard, David Lu, Kelsey Hawkins, Antonio El Khoury, Eric Cousineau, Ioan Sucan , Jackie Kay
autogenerated on Mon Feb 28 2022 23:58:25