basics.py
Go to the documentation of this file.
00001 import string
00002 import yaml
00003 import collections
00004 from lxml import etree
00005 
00006 # Different implementations mix well it seems
00007 # @todo Do not use this?
00008 from xml.etree.ElementTree import ElementTree
00009 
00010 def xml_string(rootXml, addHeader = True):
00011     # Meh
00012     xmlString = etree.tostring(rootXml, pretty_print = True)
00013     if addHeader:
00014         xmlString = '<?xml version="1.0"?>\n' + xmlString
00015     return xmlString
00016 
00017 def dict_sub(obj, keys):
00018     return dict((key, obj[key]) for key in keys)
00019 
00020 def node_add(doc, sub):
00021     if sub is None:
00022         return None
00023     if type(sub) == str:
00024         return etree.SubElement(doc, sub)
00025     elif isinstance(sub, etree._Element):
00026         doc.append(sub) # This screws up the rest of the tree for prettyprint...
00027         return sub
00028     else:
00029         raise Exception('Invalid sub value')
00030 
00031 def pfloat(x):
00032     return str(x).rstrip('.') 
00033 
00034 def xml_children(node):
00035     children = node.getchildren()
00036     def predicate(node):
00037         return not isinstance(node, etree._Comment)
00038     return filter(predicate, children)
00039 
00040 def to_yaml(obj):
00041     """ Simplify yaml representation for pretty printing """
00042     # Is there a better way to do this by adding a representation with yaml.Dumper?
00043     # Ordered dict: http://pyyaml.org/ticket/29#comment:11
00044     if obj is None or type(obj) in [str, unicode]:
00045         out = str(obj)
00046     elif type(obj) in [int, float, bool]:
00047         return obj
00048     elif hasattr(obj, 'to_yaml'):
00049         out = obj.to_yaml()
00050     elif isinstance(obj, etree._Element):
00051         out = etree.tostring(obj, pretty_print = True)
00052     elif type(obj) == dict:
00053         out = {}
00054         for (var, value) in obj.iteritems():
00055             out[str(var)] = to_yaml(value)
00056     elif hasattr(obj, 'tolist'):
00057         # For numpy objects
00058         out = to_yaml(obj.tolist())
00059     elif isinstance(obj, collections.Iterable):
00060         out = [to_yaml(item) for item in obj]
00061     else:
00062         out = str(obj)
00063     return out
00064 
00065 class SelectiveReflection(object):
00066         def get_refl_vars(self):
00067                 return vars(self).keys()
00068 
00069 class YamlReflection(SelectiveReflection):
00070         def to_yaml(self):
00071                 raw = dict((var, getattr(self, var)) for var in self.get_refl_vars())
00072                 return to_yaml(raw)
00073                 
00074         def __str__(self):
00075                 return yaml.dump(self.to_yaml()).rstrip() # Good idea? Will it remove other important things?


pr2_calibration_launch
Author(s): Vijay Pradeep
autogenerated on Wed Apr 3 2019 02:59:37