1 """Read and write files in the form
2 [label]
3 text
4 text
5 text
6 [label2]
7 text
8 text
9 ...
10
11 The format is imperfect to the extent that
12 it does not allow the text to contain things that
13 look like labels.
14
15
16 When used as a script, it selects regions of such a file
17 and prints them on the standard output:
18 Usage: named_block_file.py key1 [key2] <input >output
19 The sections labelled key1 and key2 will be output in order,
20 with no separators other than a newline in between.
21 """
22
23 import g_encode
24 import re
25
26 _label = re.compile(r"""^\[\s*(.+?)\s*\]\s*$""")
27
28 _e = g_encode.encoder(notallowed = r']\r\n%')
29
31 n = len(lines)
32 if n > 0 and lines[n-1] == '\n':
33 n -= 1
34 return ''.join(lines)
35
36
38 inlabel = None
39 lines = []
40 d = {}
41 for l in fd:
42 m = _label.match(l)
43 if m:
44 if inlabel is not None:
45 d[inlabel] = _join(lines)
46 lines = []
47 inlabel = _e.back(m.group(1))
48 else:
49 lines.append(l)
50
51 if inlabel is not None:
52 d[inlabel] = _join(lines)
53 return d
54
55
57 fd.writelines('[%s]\n' % _e.fwd(k))
58
59 -def write_text(fd, t):
61
63 fd.writelines([t, '\n'])
64
68
74
75
76
77
78
79
80 if __name__ == '__main__':
81 import sys
82 info = read(sys.stdin)
83 for k in sys.argv[1:]:
84 sys.stdout.writelines(info[k])
85