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 
11 def xml_string(rootXml, addHeader=True):
12  # Meh
13  xmlString = etree.tostring(rootXml, pretty_print=True)
14  if addHeader:
15  xmlString = '<?xml version="1.0"?>\n' + xmlString
16  return xmlString
17 
18 
19 def dict_sub(obj, keys):
20  return dict((key, obj[key]) for key in keys)
21 
22 
23 def node_add(doc, sub):
24  if sub is None:
25  return None
26  if type(sub) == str:
27  return etree.SubElement(doc, sub)
28  elif isinstance(sub, etree._Element):
29  doc.append(sub) # This screws up the rest of the tree for prettyprint
30  return sub
31  else:
32  raise Exception('Invalid sub value')
33 
34 
35 def pfloat(x):
36  return str(x).rstrip('.')
37 
38 
39 def xml_children(node):
40  children = node.getchildren()
41 
42  def predicate(node):
43  return not isinstance(node, etree._Comment)
44  return list(filter(predicate, children))
45 
46 
47 def isstring(obj):
48  try:
49  return isinstance(obj, basestring)
50  except NameError:
51  return isinstance(obj, str)
52 
53 
54 def to_yaml(obj):
55  """ Simplify yaml representation for pretty printing """
56  # Is there a better way to do this by adding a representation with
57  # yaml.Dumper?
58  # Ordered dict: http://pyyaml.org/ticket/29#comment:11
59  if obj is None or isstring(obj):
60  out = str(obj)
61  elif type(obj) in [int, float, bool]:
62  return obj
63  elif hasattr(obj, 'to_yaml'):
64  out = obj.to_yaml()
65  elif isinstance(obj, etree._Element):
66  out = etree.tostring(obj, pretty_print=True)
67  elif type(obj) == dict:
68  out = {}
69  for (var, value) in obj.items():
70  out[str(var)] = to_yaml(value)
71  elif hasattr(obj, 'tolist'):
72  # For numpy objects
73  out = to_yaml(obj.tolist())
74  elif isinstance(obj, collections.Iterable):
75  out = [to_yaml(item) for item in obj]
76  else:
77  out = str(obj)
78  return out
79 
80 
81 class SelectiveReflection(object):
82  def get_refl_vars(self):
83  return list(vars(self).keys())
84 
85 
87  def to_yaml(self):
88  raw = dict((var, getattr(self, var)) for var in self.get_refl_vars())
89  return to_yaml(raw)
90 
91  def __str__(self):
92  # Good idea? Will it remove other important things?
93  return yaml.dump(self.to_yaml()).rstrip()
def xml_string(rootXml, addHeader=True)
Definition: basics.py:11


urdfdom_py
Author(s): Thomas Moulard, David Lu, Kelsey Hawkins, Antonio El Khoury, Eric Cousineau, Ioan Sucan , Jackie Kay
autogenerated on Mon Jun 10 2019 15:36:23