basics.py
Go to the documentation of this file.
1 import string
2 import yaml
3 import collections
4 from lxml import etree
5 
6 # Different implementations mix well it seems
7 # @todo Do not use this?
8 from xml.etree.ElementTree import ElementTree
9 
10 def xml_string(rootXml, addHeader = True):
11  # Meh
12  xmlString = etree.tostring(rootXml, pretty_print = True)
13  if addHeader:
14  xmlString = '<?xml version="1.0"?>\n' + xmlString
15  return xmlString
16 
17 def dict_sub(obj, keys):
18  return dict((key, obj[key]) for key in keys)
19 
20 def node_add(doc, sub):
21  if sub is None:
22  return None
23  if type(sub) == str:
24  return etree.SubElement(doc, sub)
25  elif isinstance(sub, etree._Element):
26  doc.append(sub) # This screws up the rest of the tree for prettyprint...
27  return sub
28  else:
29  raise Exception('Invalid sub value')
30 
31 def pfloat(x):
32  return str(x).rstrip('.')
33 
34 def xml_children(node):
35  children = node.getchildren()
36  def predicate(node):
37  return not isinstance(node, etree._Comment)
38  return list(filter(predicate, children))
39 
40 def to_yaml(obj):
41  """ Simplify yaml representation for pretty printing """
42  # Is there a better way to do this by adding a representation with yaml.Dumper?
43  # Ordered dict: http://pyyaml.org/ticket/29#comment:11
44  if obj is None or type(obj) in [str, str]:
45  out = str(obj)
46  elif type(obj) in [int, float, bool]:
47  return obj
48  elif hasattr(obj, 'to_yaml'):
49  out = obj.to_yaml()
50  elif isinstance(obj, etree._Element):
51  out = etree.tostring(obj, pretty_print = True)
52  elif type(obj) == dict:
53  out = {}
54  for (var, value) in obj.items():
55  out[str(var)] = to_yaml(value)
56  elif hasattr(obj, 'tolist'):
57  # For numpy objects
58  out = to_yaml(obj.tolist())
59  elif isinstance(obj, collections.Iterable):
60  out = [to_yaml(item) for item in obj]
61  else:
62  out = str(obj)
63  return out
64 
65 class SelectiveReflection(object):
66  def get_refl_vars(self):
67  return list(vars(self).keys())
68 
70  def to_yaml(self):
71  raw = dict((var, getattr(self, var)) for var in self.get_refl_vars())
72  return to_yaml(raw)
73 
74  def __str__(self):
75  return yaml.dump(self.to_yaml()).rstrip() # Good idea? Will it remove other important things?
def xml_string(rootXml, addHeader=True)


pr2_calibration_launch
Author(s): Vijay Pradeep
autogenerated on Tue Jun 1 2021 02:50:59