Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
import sys
from optparse import OptionParser
def main():
'''Main driver.'''
parser = OptionParser()
parser.add_option('-o', '--opening',
default=None, dest='opening', help='Header string')
parser.add_option('-c', '--closing',
default=None, dest='closing', help='Footer string')
args, extras = parser.parse_args()
assert args.opening and args.closing, \
'Must specify opening (-o) and closing (-c) delimiters'
opening = closing = None
bodies = []
if not extras:
opening, content, closing = extract(args, sys.stdin)
else:
for filename in extras:
with open(filename, 'r') as reader:
o, content, c = extract(args, reader)
if opening is None:
opening = o
closing = c
bodies.append(content)
display(opening, *bodies, closing)
def extract(args, reader):
'''Extract content from named file.'''
data = reader.read()
i_opening = data.find(args.opening) + len(args.opening)
i_closing = data.rfind(args.closing)
return data[:i_opening], data[i_opening:i_closing], data[i_closing:]
def display(*blocks):
'''Display all the text.'''
for b in blocks:
print(b)
if __name__ == '__main__':
main()