Package gmisclib :: Module named_block_file
[frames] | no frames]

Source Code for Module gmisclib.named_block_file

 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   
30 -def _join(lines):
31 n = len(lines) 32 if n > 0 and lines[n-1] == '\n': 33 n -= 1 34 return ''.join(lines)
35 36
37 -def read(fd):
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
56 -def write_key(fd, k):
57 fd.writelines('[%s]\n' % _e.fwd(k))
58
59 -def write_text(fd, t):
60 fd.writelines(t)
61
62 -def write_line(fd, t):
63 fd.writelines([t, '\n'])
64
65 -def write_line_kv(fd, k, v):
66 import avio 67 fd.writelines([avio.concoct({k: v}), '\n'])
68
69 -def write(fd, d):
70 for (k, v) in d.items(): 71 write_key(fd, k) 72 write_text(fd, v) 73 fd.writelines('\n')
74 75 76 # def test(): 77 # import sys 78 # write(sys.stdout, read(sys.stdin)) 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