yat.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #
3 # @brief YAT: YAml Template text processor
4 # @date $Date: 2008-02-09 20:04:27 $
5 # @author Norkai Ando <n-ando@aist.go.jp>
6 #
7 # Copyright (C) 2008 Noriaki Ando, All rights reserved.
8 #
9 # $Id: yat.py 775 2008-07-28 16:14:45Z n-ando $
10 #
11 
12 #
13 # Usage:
14 #------------------------------------------------------------
15 # import yaml
16 # import yat
17 #
18 # dict = yaml.load(open(filename, "r").read())
19 # t = yat.Template(template, "\[", "\]")
20 # result = t.generate(dict)
21 #------------------------------------------------------------
22 #
23 # 1. Simple directive:
24 # [dictionary_key]
25 #
26 # Nested dictionaries can be expressed by dotted expression.
27 #
28 # example:
29 # dict = {"a": "This is a",
30 # "b": {"1": "This is b.1",
31 # "2": "This is b.2"}
32 # }
33 #
34 # template:
35 # [a]
36 #
37 # [b.1]
38 #
39 # [b.2]
40 #
41 # result:
42 # This is a
43 # This is b.1
44 # This is b.2
45 #
46 #
47 # 2. "for" directive:
48 # [for key in list] statement [endfor]
49 #
50 # Iterative evaluation for listed values is performed by "for" statement.
51 # In iteration at each evaluation, the value of the list is assigned to
52 # "key". The "key" also can be the nested dictionary directive.
53 #
54 # example:
55 # dict = {"list": [0, 1, 2],
56 # "listed_dict": [
57 # {"name": "x", "value": "1.0"},
58 # {"name": "y", "value": "0.2"},
59 # {"name": "z", "value": "0.1"}]}
60 #
61 # template:
62 # [for lst in list]
63 # [lst],
64 # [endfor]
65 # [for lst in listed_dict]
66 # [lst.name]: [lst.value]
67 #
68 # [endfor]
69 #
70 # result:
71 # 1, 2, 3,
72 # x: 1.0
73 # y: 0.2
74 # x: 0.1
75 #
76 #
77 # 3. "if-index" directive:
78 # [for key in val]
79 # [if-index key is first|even|odd|last|NUMBER] statement1
80 # [elif-index key is first|even|odd|last|NUMBER] statement2
81 # [endif][endfor]
82 #
83 # "if-index" is used to specify the index of the "for" iteration.
84 # The "key" string which is defined in the "for" statement is used as index.
85 # A number or predefined directives such as "first", "even", "odd" and
86 # "last" can be used to specify the index.
87 #
88 # example:
89 # dict = {"list": [0,1,2,3,4,5,6,7,8,9,10]}
90 #
91 # template:
92 # [for key in list]
93 # [if-index key is 3] [key] is hoge!!
94 # [elif-index key is 6] [key] is foo!!
95 # [elif-index key is 9] [key] is bar!!
96 # [elif-index key is first] [key] is first
97 # [elif-index key is last] Omoro-------!!!!
98 # [elif-index key is odd] [key] is odd number
99 # [elif-index key is even] [key] is even number
100 # [endif]
101 # [endfor]
102 #
103 # result:
104 # 0 is first
105 # 1 is odd number
106 # 2 is even number
107 # 3 is hoge!!
108 # 4 is even number
109 # 5 is odd number
110 # 6 is foo!!
111 # 7 is odd number
112 # 8 is even number
113 # 9 is bar!!
114 # Omoro-------!!!!
115 #
116 #
117 # 4. "if" directive: [if key is value] text1 [else] text2 [endif]
118 # If "key" is "value", "text1" appears, otherwise "text2" appears.
119 #
120 # example:
121 # dict = {"key1": "a", "key2": "b"}
122 #
123 # template:
124 # [if key1 is a]
125 # The key1 is "a".
126 # [else]
127 # This key1 is not "a".
128 # [endif]
129 #
130 # result:
131 # The key1 is "a".
132 #
133 #
134 # 5. "if-any" directive: [if-any key1] text1 [else] text2 [endif]
135 # If the "key1" exists in the dictionary, "text1" appears, otherwise
136 # "text2" appears.
137 #
138 # example:
139 # dict = {"key1": "a", "key2": "b"}
140 #
141 # template:
142 # [if-any key1]
143 # key1 exists.
144 # [endif][if-any key3]
145 # key3 exists.
146 # [else]
147 # key3 does not exists.
148 # [endif]
149 #
150 # result:
151 # key1 exists.
152 # key3 does not exists.
153 #
154 #
155 # 6. bracket and comment:
156 # [[] is left bracket if begin mark is "["
157 # [# comment ] is comment if begin/end marks are "[" and "]"
158 #
159 # example:
160 # dict = {}
161 #
162 # template:
163 # [[]bracket]
164 # [# comment]
165 #
166 # result:
167 # [bracket]
168 #
169 import string
170 import re
171 from types import StringType, IntType, FloatType, DictType, ListType, ClassType
172 import sys
173 
174 class Template:
175  """
176  usage:
177  tempalte_text = read template text from file
178  dictionary = create dictionaly by using yaml
179  t = Template(tempalte_text)
180  generated_text = t.generate(dictionary)
181 
182  """
183 
184  def __init__(self, template, begin_mark="\[", end_mark="\]"):
185  self.__procs = [self.__proc_text,
186  self.__proc_cmd,
187  self.__proc_bracket]
188  self.template = template
189 
190  # regular expression to devide text into DIRECTIVE, BRACKET and COMMENT
191  #
192  # default:
193  # START_MARK: "["
194  # END_MARK : "]"
195  # -> START_MARK and END_MARK can be given in ctor
196  #
197  # ITEM: (?:"(?:[^\\"]|\\.)*"|[-\w.]+)
198  # \[(ITEM(?: +ITEM)*)\]|(\[\[\])|\[#[^\]]*\]
199  # ~~~~~~~~(1)~~~~~~ ~~(2)~~~ ~~~(3)~~~~~
200  # (1) COMMAND : '[' ITEM (whitespace ITEM)* ']
201  # ITEM : STRING | NAME
202  # STRING : '"' (not-slash-or-dquote | '\' anychar)* '"'
203  # NAME : (alphanum | '_' | '-' | '.')+
204  # (2) BEGIN_MARK_ESCAPE : '[[]'
205  # (3) COMMENT : '[#' not-rbracket
206  #
207  # re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.]+)'
208  # re_command = r'\[(%s(?: +%s)*)\]' % (re_item, re_item)
209  # re_beginmark = r'\[\[\]'
210  # re_comment = r'\[#[^\]]*\]'
211  # re_parse = re.compile(r'%s|(%s)|%s'
212  # % (re_command, re_beginmark, re_comment))
213  # re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.]+')
214  #
215  #
216  re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.:]+)'
217  re_command = r'%s(%s(?: +%s)*)%s' % \
218  (begin_mark, re_item, re_item, end_mark)
219  re_bracket = r'%s%s%s' % \
220  (begin_mark, begin_mark, end_mark)
221  re_comment = r'%s#[^%s]*%s' % \
222  (begin_mark, end_mark, end_mark)
223  self.begin_mark = begin_mark.replace("\\","")
224  self.re_parse = re.compile(r'%s|(%s)|%s' % \
225  (re_command, re_bracket, re_comment))
226  self.re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.:]+')
227  self.re_number = re.compile(r'[0-9]+')
228 
229  # tokenize input text
230  self.token = self.re_parse.split(self.template)
231  self.token_len = len(self.token)
232 
233  # initialize variables
234  self.script = program
235  self.indent = 4
236  self.script_level = 2
237  self.level = 0
238  self.index = 0
239  self.cmd_cxt = []
240 
241  # parse token
242  self.__parse_template(self.token)
243 
244  return
245 
246  def generate(self, dict):
247  # eval generated script
248  exec(self.script)
249  # script includes Generator class
250  gen = Generator(self.token, dict)
251  # execute generated script
252  return gen.generate()
253 
254  def get_script(self):
255  return self.script
256 
257  def __push_level(self):
258  self.level += 1
259 
260  def __pop_level(self):
261  self.level -= 1
262 
263  def __write_cmd(self, cmd):
264  tmp_cmd = self.__indent()
265  tmp_cmd += "self.set_index(%s)\n" % (self.index)
266  self.script += tmp_cmd
267  self.__write_cmd_noindex(cmd)
268 
269  def __write_cmd_noindex(self, cmd):
270  tmp_cmd = self.__indent()
271  tmp_cmd += cmd + "\n"
272  self.script += tmp_cmd
273 
274  def __parse_template(self, dict):
275  try:
276  # split into (TEXT DIRECTIVE BRACKET)* TEXT
277  self.__parse()
278  except YATException, e:
279  self.__print_error(e)
280  sys.exit(-1)
281 
282  def __indent(self):
283  indent = " " * ((self.script_level + self.level) * self.indent)
284  return indent
285 
286  def __parse(self):
287  while self.index < self.token_len:
288  self.__procs[self.index % 3]()
289  self.index += 1
290 
291  def __proc_text(self):
292  if self.token[self.index] == None:
293  return
294  cmd_text = "self.write_token(%s)" % (self.index)
295  self.__write_cmd(cmd_text)
296  return True
297 
298  def __proc_bracket(self):
299  if self.token[self.index] == None:
300  return
301  cmd_text = "self.write(\"" + self.begin_mark + "\")"
302  self.__write_cmd(cmd_text)
303  return True
304 
305  def __proc_cmd(self):
306  cmd = self.token[self.index]
307  try:
308  args = self.re_args.findall(cmd)
309  except:
310  return
311  self.del_nl_after_cmd()
312  argc = len(args)
313  if argc == 0:
314  raise InvalidDirective(self.lineno(), "_an empty directive_ ")
315 
316  # simple directive
317  if argc == 1:
318  if args[0] == "endfor":
319  self.__endfor_cmd(args)
320  return
321  elif args[0] == "else":
322  self.__else_cmd(args)
323  return
324  elif args[0] == "last":
325  self.__last_cmd(args)
326  return
327  elif args[0] == "endif":
328  self.__endif_cmd(args)
329  return
330  else:
331  self.__cmd(args)
332  return
333  elif argc == 2:
334  if args[0] == "if-any":
335  self.__if_any_cmd(args)
336  return
337  elif argc == 4: # [for key in value]
338  if args[0] == "for" and args[2] == "in":
339  self.__for_cmd(args)
340  return True
341  elif args[0] == "if" and args[2] == "is":
342  self.__if_cmd(args)
343  elif args[0] == "elif" and args[2] == "is":
344  self.__elif_cmd(args)
345  elif args[0] == "if-index" and args[2] == "is":
346  self.__if_index_cmd(args)
347  elif args[0] == "elif-index" and args[2] == "is":
348  self.__elif_index_cmd(args)
349  else:
350  raise InvalidDirective(self.lineno(), cmd)
351  else:
352  raise InvalidDirective(self.lineno(), cmd)
353  return True
354 
355  def __cmd(self, args):
356  cmd_text = "self.write_dict(\"%s\")" % (args[0])
357  self.__write_cmd(cmd_text)
358 
359  #------------------------------------------------------------
360  # [for] commands
361  # - for
362  # - last
363  # - endfor
364  #------------------------------------------------------------
365  def __for_cmd(self, args):
366  """
367  The following [for] directive
368  [for tmp_key in directive]
369  is converted into the following python command.
370  for i in len(directive):
371  self.dicts.append({tmp_key: ditective[i])
372  and, endfor directive terminate as the following,
373  self.dicts.pop()
374  """
375  key = args[1]
376  directive = args[3]
377  # (key) : variable string of index variable for [for] block
378  # (key)_list: list value of specified directive
379  # (key)_len : length of the list
380  cmd_text = "%s_list = self.get_list(\"%s\")" % (key, directive)
381  self.__write_cmd(cmd_text)
382  cmd_text = "%s_len = len(%s_list)" % (key, key)
383  self.__write_cmd(cmd_text)
384  cmd_text = "for %s_index in range(len(%s_list)):" % (key, key)
385  self.__write_cmd(cmd_text)
386  self.__push_level()
387  cmd_text = "self.push_dict({\"%s\": %s_list[%s_index]})" \
388  % (key, key, key)
389  self.__write_cmd(cmd_text)
390  self.cmd_cxt.append("for")
391 
392  def __endfor_cmd(self, args):
393  try:
394  cxt = self.cmd_cxt.pop()
395  if cxt != "for":
396  raise UnmatchedBlock(self.lineno(), "endfor")
397  self.__write_cmd("self.pop_dict()")
398  self.__pop_level()
399  except:
400  print args, self.lineno()
401  raise UnmatchedBlock(self.lineno(), "endfor")
402  return
403 
404  # end of [for] commands
405  #------------------------------------------------------------
406 
407  #------------------------------------------------------------
408  # [if] commands
409  # - if
410  # - if-index
411  # - if-any
412  #------------------------------------------------------------
413  def __if_cmd(self, args):
414  """
415  The following [if] directive
416  [if directive is string]
417  is converted into the following python command.
418  if self.__get_string() == "string":
419  """
420  directive = args[1]
421  string = args[3]
422  cmd_text = "if self.get_text(\"%s\") == \"%s\":" % \
423  (directive, string)
424  self.__write_cmd(cmd_text)
425  self.__push_level()
426  self.cmd_cxt.append("if")
427  return
428 
429  def __elif_cmd(self, args):
430  if self.cmd_cxt[-1] != "if":
431  raise UnmatchedBlock(self.lineno(), "elif")
432  directive = args[1]
433  string = args[3]
434  cmd_text = "elif self.get_text(\"%s\") == \"%s\":" % \
435  (directive, string)
436  self.__pop_level()
437  self.__write_cmd_noindex(cmd_text)
438  self.__push_level()
439  return
440 
441  # [if-index] commands
442  def __if_index_cmd(self, args):
443  # [if-index KEY is [first|even|odd|last|NUMBER]]
444  # ~~~0~~~ ~1~ 2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~
445  cmdlist = {"first": "if %s_index == 0:",
446  "even" : "if (%s_index %% 2) == 0:",
447  "odd" : "if (%s_index %% 2) != 0:",
448  "last" : "if %s_index == %s_len - 1:"}
449  key = args[1]
450  cmd = args[3]
451  if len(self.re_number.findall(cmd)) == 1:
452  cmd_text = "if %s_index == %s:" % (key, cmd)
453  elif cmdlist.has_key(cmd):
454  if cmd == "last":
455  cmd_text = cmdlist[cmd] % (key,key)
456  else:
457  cmd_text = cmdlist[cmd] % (key)
458  else:
459  raise InvalidDirective(self.lineno(), ''.join(args))
460  self.__write_cmd(cmd_text)
461  self.__push_level()
462  self.cmd_cxt.append("if-index")
463 
464  def __elif_index_cmd(self, args):
465  if self.cmd_cxt[-1] != "if-index":
466  raise UnmatchedBlock(self.lineno(), "elif-index")
467  # [elif-index KEY is [first|even|odd|last|NUMBER]]
468  # ~~~0~~~ ~1~ 2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~
469  cmdlist = {"first": "elif %s_index == 0:",
470  "even" : "elif (%s_index %% 2) == 0:",
471  "odd" : "elif (%s_index %% 2) != 0:",
472  "last" : "elif %s_index == %s_len - 1:"}
473  key = args[1]
474  cmd = args[3]
475  if len(self.re_number.findall(cmd)) == 1:
476  cmd_text = "elif %s_index == %s:" % (key, cmd)
477  elif cmdlist.has_key(cmd):
478  if cmd == "last":
479  cmd_text = cmdlist[cmd] % (key,key)
480  else:
481  cmd_text = cmdlist[cmd] % (key)
482  else:
483  raise InvalidDirective(self.lineno(), ' '.join(args))
484  self.__pop_level()
485  self.__write_cmd_noindex(cmd_text)
486  self.__push_level()
487 
488  # [if-any] command
489  def __if_any_cmd(self, args):
490  directive = args[1]
491  cmd_text = "if self.has_key(\"%s\"):" % (directive)
492  self.__write_cmd(cmd_text)
493  self.__push_level()
494  self.cmd_cxt.append("if-any")
495  return
496 
497  def __elif_any_cmd(self, args):
498  if self.cmd_cxt[-1] != "if-any":
499  raise UnmatchedBlock(self.lineno(), "elif-any")
500  directive = args[1]
501  cmd_text = "if self.has_key(\"%s\"):" % (directive)
502  self.__pop_level()
503  self.__write_cmd_noindex(cmd_text)
504  self.__push_level()
505  return
506 
507  # [else], [endif] commands
508  def __else_cmd(self, args):
509  if self.cmd_cxt[-1] != "if" and self.cmd_cxt[-1] != "if-index" \
510  and self.cmd_cxt[-1] != "if-any":
511  raise UnmatchedBlock(self.lineno(), "else")
512  self.__pop_level()
513  self.__write_cmd_noindex("else:")
514  self.__push_level()
515  return
516 
517  def __endif_cmd(self, args):
518  if self.cmd_cxt[-1] != "if" and self.cmd_cxt[-1] != "if-index" \
519  and self.cmd_cxt[-1] != "if-any":
520  raise UnmatchedBlock(self.lineno(), "endif")
521  self.cmd_cxt.pop()
522  self.__pop_level()
523  return
524  # end of [if] commands
525  #------------------------------------------------------------
526 
527  def __print_error(self, e):
528  print "Parse Error: line", e.lineno, "in input data"
529  print " " + ''.join(nesteditem(e.value))
530  lines = self.template.split("\n")
531  length = len(lines)
532  print "------------------------------------------------------------"
533  for i in range(1,10):
534  l = e.lineno - 6 + i
535  if l > 0 and l < length:
536  print lines[l]
537  if i == 5:
538  uline = '~'*len(lines[l])
539  print uline
540  print "------------------------------------------------------------"
541 
542  def del_nl_after_cmd(self):
543  # next text index after command
544  next = self.index + 2
545  if next > self.token_len: return
546  if self.token[next] == None: return
547  text = self.token[next]
548  tlen = len(text)
549  if tlen > 0 and text[0] == '\n':
550  self.token[next] = text[1:]
551  return
552  elif tlen > 0 and text[0] == '\r':
553  self.token[next] = text[1:]
554  return
555  elif tlen > 1 and text[0:2] == '\r\n':
556  self.token[next] = text[2:]
557 
558  def lineno(self):
559  l = 1
560  for i in range(self.index):
561  if isinstance(self.token[i], StringType):
562  l += self.token[i].count('\n')
563  for i in range(1, self.index, 3):
564  l += 1
565  return l
566 
567 
568 #------------------------------------------------------------
569 # Generator and GeneratorBase classes
570 #------------------------------------------------------------
571 program = """
572 class Generator(GeneratorBase):
573  def __init__(self, token, dict):
574  GeneratorBase.__init__(self, token, dict)
575  def generate(self):
576  try:
577  self.process()
578  except YATException, e:
579  self.print_error(e)
580  sys.exit(-1)
581  return self.text
582 
583  def process(self):
584 """
585 
587  def __init__(self, token, dict):
588  self.token = token
589  self.dicts = [dict]
590  self.index = 0
591  self.text = ""
592 
593  def print_error(self, e):
594  print "\nTemplate Generation Error: line", e.lineno, "in input data"
595  print " " + ''.join(nesteditem(e.value))
596  temp = ""
597  for i, s in enumerate(self.token):
598  if s != None:
599  if i % 3 == 1:
600  temp += "[" + s + "]\n"
601  else:
602  temp += s
603  lines = temp.split("\n")
604  length = len(lines)
605  print "------------------------------------------------------------"
606  for i in range(1,10):
607  l = e.lineno - 6 + i
608  if l > 0 and l < length:
609  print lines[l]
610  if i == 5:
611  uline = '~'*len(lines[l])
612  print uline
613  print "------------------------------------------------------------"
614 
615  def set_index(self, index):
616  self.index = index
617 
618  def push_dict(self, dict):
619  self.dicts.append(dict)
620 
621  def pop_dict(self):
622  if len(self.dicts) < 2:
623  raise UnmatchedBlock(self.lineno(), "")
624  self.dicts.pop()
625 
626  def write(self, text):
627  self.text += text
628 
629  def write_dict(self, keytext):
630  self.write(self.get_text(keytext))
631 
632  def write_token(self, index):
633  self.write(self.token[index])
634 
635  def lineno(self):
636  cnt = 1
637  for i in range(0, self.index, 3):
638  if self.token[i] != None:
639  cnt += self.token[i].count('\n')
640  # count deleted '\n' after commands
641  for i in range(1, self.index, 3):
642  if self.token[i] != None:
643  cnt += 1
644  return cnt
645 
646  def get_text(self, keytext):
647  val = self.get_value(keytext)
648  if isinstance(val, StringType):
649  return val
650  if isinstance(val, IntType) or isinstance(val, FloatType):
651  return str(val)
652  raise UnexpectedData(self.lineno(), "\"" + keytext + \
653  "\" should have string, int or float value.")
654 
655  def get_list(self, keytext):
656  val = self.get_value(keytext)
657  if not isinstance(val, ListType):
658  raise UnexpectedData(self.lineno(),
659  "\"" + keytext + "\" should have list value.")
660  return val
661 
662  def has_key(self, keytext):
663  try:
664  self.get_value(keytext)
665  return True
666  except NotFound, e:
667  return False
668 
669  def get_value(self, keytext):
670  keys = keytext.split('.')
671  for i in range(len(self.dicts) - 1, -1, -1):
672  dict_value = self.get_dict_value(keys, self.dicts[i])
673  if dict_value != None:
674  return dict_value
675  raise NotFound(self.lineno(), keytext)
676 
677  def get_dict_value(self, keys, dict):
678  length = len(keys)
679  d = dict
680  for i in range(length):
681  if isinstance(d, DictType) and d.has_key(keys[i]):
682  d = d[keys[i]]
683  else:
684  return None
685  return d
686 
687 
688 #------------------------------------------------------------
689 # Exceptions
690 #------------------------------------------------------------
691 class YATException(Exception):
692  pass
693 
694 class UnknownError(YATException):
695  def __init__(self, lineno):
696  self.lineno = lineno
697  self.value = "Unknown error."
698 
700  def __init__(self, lineno, msg):
701  self.lineno = lineno
702  self.value = "Unmatched block error: " + msg
703 
705  def __init__(self, lineno, msg):
706  self.lineno = lineno
707  self.value = msg
708 
710  def __init__(self, dictkey, dictvalue):
711  self.value = "Specified key is not final element: ",\
712  dictkey, "=>", dictvalue
713 
715  def __init__(self, lineno, directive):
716  self.lineno = lineno
717  self.value = "Invalid directive: \"[" + directive + "]\""
718 
720  def __init__(self, lineno, description):
721  self.lineno = lineno
722  self.value = "Unmatched data and input: ", description
723 
725  def __init__(self, lineno, description):
726  self.lineno = lineno
727  self.value = "Value not found for: \"" + description + "\""
728 
729 #------------------------------------------------------------
730 # other functions
731 #------------------------------------------------------------
732 def nesteditem(aList):
733  for anItem in aList:
734  if type(anItem)==list:
735  for subitem in nesteditem(anItem):
736  yield subitem
737  else:
738  yield anItem
739 
740 
741 
742 if __name__ == "__main__":
743  dict = []
744  template = []
745  #------------------------------------------------------------
746  # Example 0
747  #------------------------------------------------------------
748  dict.append({"a": "This is a",
749  "b": {"1": "This is b.1",
750  "2": "This is b.2"}
751  })
752  template.append("""[a]
753 
754 [b.1]
755 
756 [b.2]""")
757 
758  #------------------------------------------------------------
759  # Example 1
760  #------------------------------------------------------------
761  dict.append({"list": [0, 1, 2],
762  "listed_dict": [
763  {"name": "x", "value": "1.0"},
764  {"name": "y", "value": "0.2"},
765  {"name": "z", "value": "0.1"}]})
766  template.append("""[for lst in list]
767 [lst],
768 [endfor]
769 [for lst in listed_dict]
770 [lst.name]: [lst.value]
771 
772 [endfor]""")
773 
774  #------------------------------------------------------------
775  # Example 2
776  #------------------------------------------------------------
777  dict.append({"list": [0,1,2,3,4,5,6,7,8,9,10]})
778  template.append("""[for key in list]
779 [if-index key is 3] [key] is hoge!!
780 [elif-index key is 6] [key] is foo!!
781 [elif-index key is 9] [key] is bar!!
782 [elif-index key is first] [key] is first
783 [elif-index key is last] Omoro-------!!!!
784 [elif-index key is odd] [key] is odd number
785 [elif-index key is even] [key] is even number
786 [endif]
787 [endfor]""")
788 
789  #------------------------------------------------------------
790  # Example 3
791  #------------------------------------------------------------
792  dict.append({"key1": "a", "key2": "b"})
793  template.append("""[if key1 is a]
794 The key1 is "a".
795 [else]
796 This key1 is not "a".
797 [endif]""")
798 
799  #------------------------------------------------------------
800  # Example 4
801  #------------------------------------------------------------
802  dict.append({"key1": "a", "key2": "b"})
803  template.append("""[if-any key1]
804 key1 exists.
805 [endif][if-any key3]
806 key3 exists.
807 [else]
808 key3 does not exists.
809 [endif]""")
810 
811  dict.append({})
812  template.append("""
813 [[]bracket]
814 [# comment]
815 """)
816 
817  import yaml
818  if len(dict) == len(template):
819  for i in range(len(dict)-1,len(dict)):
820  t = Template(template[i])
821  print "-" * 60
822  print "Example:", i
823  print "-" * 60
824  print "Template:\n"
825  print template[i]
826  print "-" * 60
827  print "Dictionary:\n"
828  print yaml.dump(dict[i], default_flow_style=False)
829  print "-" * 60
830  print "Generated Script:\n"
831  print t.get_script()
832  print "-" * 60
833  print "Generated Text:\n"
834  print t.generate(dict[i])
835  print ""
def write_token(self, index)
Definition: yat.py:632
def __write_cmd(self, cmd)
Definition: yat.py:263
def __cmd(self, args)
Definition: yat.py:355
def __if_index_cmd(self, args)
Definition: yat.py:442
def lineno(self)
Definition: yat.py:635
def write(self, text)
Definition: yat.py:626
def __init__(self, template, begin_mark="\, end_mark="\")
Definition: yat.py:184
def __proc_cmd(self)
Definition: yat.py:305
def get_dict_value(self, keys, dict)
Definition: yat.py:677
def __print_error(self, e)
Definition: yat.py:527
def split(input, delimiter)
Split string by delimiter.
Definition: StringUtil.py:323
def __pop_level(self)
Definition: yat.py:260
def has_key(self, keytext)
Definition: yat.py:662
def get_list(self, keytext)
Definition: yat.py:655
def __init__(self, lineno, description)
Definition: yat.py:720
begin_mark
Definition: yat.py:223
def __if_cmd(self, args)
Definition: yat.py:413
def __indent(self)
Definition: yat.py:282
def pop_dict(self)
Definition: yat.py:621
def del_nl_after_cmd(self)
Definition: yat.py:542
def push_dict(self, dict)
Definition: yat.py:618
def __init__(self, lineno)
Definition: yat.py:695
def __init__(self, lineno, msg)
Definition: yat.py:700
def __elif_index_cmd(self, args)
Definition: yat.py:464
def __parse(self)
Definition: yat.py:286
def __init__(self, lineno, directive)
Definition: yat.py:715
def __proc_bracket(self)
Definition: yat.py:298
def set_index(self, index)
Definition: yat.py:615
def generate(self, dict)
Definition: yat.py:246
def __parse_template(self, dict)
Definition: yat.py:274
script_level
Definition: yat.py:236
def __endfor_cmd(self, args)
Definition: yat.py:392
def get_text(self, keytext)
Definition: yat.py:646
def __elif_any_cmd(self, args)
Definition: yat.py:497
def get_value(self, keytext)
Definition: yat.py:669
def print_error(self, e)
Definition: yat.py:593
def write_dict(self, keytext)
Definition: yat.py:629
def __elif_cmd(self, args)
Definition: yat.py:429
def __endif_cmd(self, args)
Definition: yat.py:517
def __init__(self, lineno, description)
Definition: yat.py:725
def __init__(self, lineno, msg)
Definition: yat.py:705
def get_script(self)
Definition: yat.py:254
def __proc_text(self)
Definition: yat.py:291
def append(dest, src)
Definition: NVUtil.py:386
def __write_cmd_noindex(self, cmd)
Definition: yat.py:269
def __init__(self, dictkey, dictvalue)
Definition: yat.py:710
def nesteditem(aList)
Definition: yat.py:732
def __push_level(self)
Definition: yat.py:257
def __else_cmd(self, args)
Definition: yat.py:508
def __if_any_cmd(self, args)
Definition: yat.py:489
def lineno(self)
Definition: yat.py:558
def __init__(self, token, dict)
Definition: yat.py:587
def __for_cmd(self, args)
Definition: yat.py:365


openrtm_aist_python
Author(s): Shinji Kurihara
autogenerated on Mon Feb 28 2022 23:01:07