srt_file_template.py
Go to the documentation of this file.
1 #
2 # This guy will read an input file and sub for strings of the form
3 # "${blah}", and replace them with the contents of a dictionary that
4 # has the key "blah" in it. A nice way to do string subsitiution when
5 # generating a file from a template.
6 #
7 # Created by Gordon Watts (Brown) November 1997
8 
9 import regex
10 import regsub
11 
12 def file_template (output_handle, input_file_name, dictionary):
13  #
14  # Open the input file
15  #
16 
17  input_handle = open (input_file_name, "r")
18 
19  #
20  # Now, read the input to the output
21  #
22 
23  line = input_handle.readline()
24  while (line != ""):
25  output_handle.write(translate_line(line, dictionary))
26  line = input_handle.readline()
27 
28  #
29  # Done, close the input file
30  #
31 
32  input_handle.close()
33 
34 
35 #
36 # translate_line
37 #
38 # Do subsitution for a single line. Don't use the regsub module because
39 # something strange happens when replacing with double "\"s.
40 #
41 find_sub = regex.compile("\${\([^{} ]+\)}")
42 find_if = regex.compile("\${if \([^{} ]+\)}")
43 find_end = regex.compile("\${end}")
44 find_start = regex.compile("\${")
45 add_to_line_ok = 1
46 if_stack = [1]
47 def translate_line (line, dict):
48  global add_to_line_ok
49 
50  result = ""
51  remaining_line = line
52  while find_start.search(remaining_line) != -1:
53  #
54  # Get rid of everything before the start of the ${.
55  #
56 
57  (start_pos, finish_pos) = find_start.regs[0]
58  if add_to_line_ok:
59  result = result + remaining_line[:start_pos]
60  remaining_line = remaining_line[start_pos:]
61 
62  #
63  # Now, figure out what kind of thing we are looking at
64  #
65 
66  if find_if.search (remaining_line) == 0:
67  if_is_true = 0
68  if dict.has_key(find_if.group(1)):
69  if_is_true = 1
70  if_stack.insert (0, if_is_true)
71  add_to_line_ok = if_is_true
72  end_of_string = find_if.regs[0][1]
73 
74  elif find_end.search(remaining_line) == 0:
75  if len (if_stack) == 1:
76  raise "Too many ${end} in template file!"
77  del if_stack[0:1]
78  add_to_line_ok = if_stack[0]
79  end_of_string = find_end.regs[0][1]
80 
81  elif find_sub.search(remaining_line) == 0:
82  if add_to_line_ok:
83  if dict.has_key(find_sub.group(1)):
84  result = result + dict[find_sub.group(1)]
85  end_of_string = find_sub.regs[0][1]
86  else:
87  end_of_string = 0
88 
89  #
90  # And remove anything we have looked at from remaining_line
91  #
92 
93  remaining_line = remaining_line[end_of_string:]
94 
95  #
96  # This means remaining line doesn't have anything interesting left on it. That means
97  # we need to just do the append
98  #
99 
100  if add_to_line_ok:
101  result = result + remaining_line
102 
103  #
104  # Done!
105  #
106 
107  return result
def file_template(output_handle, input_file_name, dictionary)
def translate_line(line, dict)