yaml_utils.py
Go to the documentation of this file.
1 # NOTE: This is a plain copy from actionlib/tools/library.py
2 #
3 # Software License Agreement (BSD License)
4 #
5 # Copyright (c) 2010, Willow Garage, Inc.
6 # All rights reserved.
7 #
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions
10 # are met:
11 #
12 # * Redistributions of source code must retain the above copyright
13 # notice, this list of conditions and the following disclaimer.
14 # * Redistributions in binary form must reproduce the above
15 # copyright notice, this list of conditions and the following
16 # disclaimer in the documentation and/or other materials provided
17 # with the distribution.
18 # * Neither the name of Willow Garage, Inc. nor the names of its
19 # contributors may be used to endorse or promote products derived
20 # from this software without specific prior written permission.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 # POSSIBILITY OF SUCH DAMAGE.
34 #
35 # Revision $Id: library.py 9993 2010-06-09 02:35:02Z kwc $
36 """
37 Top-level library routines we expose to the end-user
38 """
39 
40 from __future__ import with_statement
41 
42 from builtins import int # matches both int and long on Py2
43 
44 import roslib.message
45 import roslib.packages
46 import rospy
47 import yaml
48 
49 
50 def findros(pkg, resource):
51  """
52  Find ROS resource inside of a package.
53 
54  @param pkg: ROS package name
55  @type pkg: str
56  @param resource: resource filename
57  @type resource: str
58  """
59  val = roslib.packages.find_resource(pkg, resource)
60  if val:
61  return val[0]
62  else:
63  raise rospy.ROSException("cannot find resource")
64 
65 
66 def YAMLBag(object):
67  def __init__(self, filename):
68  self.filename = filename
69  self._fp = open(filename, 'w')
70 
71  def append(self, msg):
72  self._fp.write(to_yaml(msg))
73 
74  def close(self):
75  if self._fp is not None:
76  self._fp.close()
77  self._fp = None
78 
79 
80 def to_yaml(obj):
81  if isinstance(obj, roslib.message.Message):
82  return _message_to_yaml(obj)
83  pass
84  else:
85  return yaml.dump(obj)
86 
87 
88 def yaml_msg_str(type_, yaml_str, filename=None):
89  """
90  Load single message from YAML dictionary representation.
91 
92  @param type_: Message class
93  @type type_: class (Message subclass)
94  @param filename: Name of YAML file
95  @type filename: str
96  """
97  import yaml
98  if yaml_str.strip() == '':
99  msg_dict = {}
100  else:
101  msg_dict = yaml.load(yaml_str)
102  if not isinstance(msg_dict, dict):
103  if filename:
104  raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
105  else:
106  raise ValueError("yaml string does not contain a dictionary")
107  m = type_()
108  roslib.message.fill_message_args(m, [msg_dict])
109  return m
110 
111 
112 def yaml_msg(type_, filename):
113  """
114  Load single message from YAML dictionary representation.
115 
116  @param type_: Message class
117  @type type_: class (Message subclass)
118  @param filename: Name of YAML file
119  @type filename: str
120  """
121  with open(filename, 'r') as f:
122  return yaml_msg_str(type_, f.read(), filename=filename)
123 
124 
125 def yaml_msgs_str(type_, yaml_str, filename=None):
126  """
127  Load messages from YAML list-of-dictionaries representation.
128 
129  @param type_: Message class
130  @type type_: class (Message subclass)
131  @param filename: Name of YAML file
132  @type filename: str
133  """
134  import yaml
135  yaml_doc = yaml.load(yaml_str)
136  msgs = []
137  for msg_dict in yaml_doc:
138  if not isinstance(msg_dict, dict):
139  if filename:
140  raise ValueError("yaml file [%s] does not contain a list of dictionaries" % filename)
141  else:
142  raise ValueError("yaml string does not contain a list of dictionaries")
143  m = type_()
144  roslib.message.fill_message_args(m, msg_dict)
145  msgs.append(m)
146  return msgs
147 
148 
149 def yaml_msgs(type_, filename):
150  """
151  Load messages from YAML list-of-dictionaries representation.
152 
153  @param type_: Message class
154  @type type_: class (Message subclass)
155  @param filename: Name of YAML file
156  @type filename: str
157  """
158  with open(filename, 'r') as f:
159  return yaml_msgs_str(type_, f.read(), filename=filename)
160 
161 
162 def _message_to_yaml(msg, indent='', time_offset=None):
163  """
164  convert value to YAML representation
165  @param val: to convert to string representation. Most likely a Message.
166  @type val: Value
167  @param indent: indentation
168  @type indent: str
169  @param time_offset: if not None, time fields will be displayed
170  as deltas from time_offset
171  @type time_offset: Time
172  """
173  if type(msg) in [int, float, str, bool]:
174  # TODO: need to actually escape
175  return msg
176  elif isinstance(msg, rospy.Time) or isinstance(msg, rospy.Duration):
177  if time_offset is not None and isinstance(msg, rospy.Time):
178  msg = msg-time_offset
179 
180  return '\n%ssecs: %s\n%snsecs: %s' % (indent, msg.secs, indent, msg.nsecs)
181 
182  elif type(msg) in [list, tuple]:
183  # have to convert tuple->list to be yaml-safe
184  if len(msg) == 0:
185  return str(list(msg))
186  msg0 = msg[0]
187  if type(msg0) in [int, float, str, bool] or \
188  isinstance(msg0, rospy.Time) or isinstance(msg0, rospy.Duration) or \
189  isinstance(msg0, list) or isinstance(msg0, tuple):
190  # no array-of-arrays support yet
191  return str(list(msg))
192  else:
193  indent = indent + ' '
194  return "["+','.join([roslib.message.strify_message(v, indent, time_offset) for v in msg])+"]"
195  elif isinstance(msg, rospy.Message):
196  if indent:
197  return '\n' + \
198  '\n'.join(['%s%s: %s' % (
199  indent, f, roslib.message.strify_message(getattr(msg, f), ' ' + indent, time_offset)) for f in msg.__slots__])
200  return '\n'.join(['%s%s: %s' % (indent, f, roslib.message.strify_message(getattr(msg, f), ' ' + indent, time_offset)) for f in msg.__slots__])
201  else:
202  return str(msg) # punt
rx_service_tools.yaml_utils.yaml_msgs_str
def yaml_msgs_str(type_, yaml_str, filename=None)
Definition: yaml_utils.py:125
rx_service_tools.yaml_utils.yaml_msg_str
def yaml_msg_str(type_, yaml_str, filename=None)
Definition: yaml_utils.py:88
rx_service_tools.yaml_utils.yaml_msg
def yaml_msg(type_, filename)
Definition: yaml_utils.py:112
rx_service_tools.yaml_utils.to_yaml
def to_yaml(obj)
Definition: yaml_utils.py:80
rx_service_tools.yaml_utils._message_to_yaml
def _message_to_yaml(msg, indent='', time_offset=None)
Definition: yaml_utils.py:162
rx_service_tools.yaml_utils.findros
def findros(pkg, resource)
Definition: yaml_utils.py:50
rx_service_tools.yaml_utils.YAMLBag
def YAMLBag(object)
Definition: yaml_utils.py:66
rx_service_tools.yaml_utils.yaml_msgs
def yaml_msgs(type_, filename)
Definition: yaml_utils.py:149


rx_service_tools
Author(s): Alireza Hosseini , Felix Widmaier
autogenerated on Thu Mar 17 2022 02:57:10