Browse Source

use "with" to handle files

master
Ben Savage 7 years ago
parent
commit
d3b8668801
  1. 63
      stanza

63
stanza

@ -36,39 +36,36 @@ def debug(line):
debug(pformat(args)) debug(pformat(args))
# Set up the file handle, <file> or stdin # Set up the file handle, <file> or stdin
if cmd.filename: with open(cmd.filename,'r') if cmd.filename else sys.stdin as handle:
handle=open(cmd.filename) # Go over the handle, line by line
else: for line in handle:
handle=sys.stdin # Start buffering if we hit the start regex
# Go over the handle, line by line if re.search(start,line):
for line in handle: buffering=True
# Start buffering if we hit the start regex debug('Started buffering on '+start)
if re.search(start,line):
buffering=True # Continue buffering if we've already started
debug('Started buffering on '+start) if buffering:
output+=line
# Continue buffering if we've already started
if buffering:
output+=line
# If a line in the stanza matches, we output the stanza # If a line in the stanza matches, we output the stanza
if buffering and re.search(match,line): if buffering and re.search(match,line):
matched=True matched=True
debug('Matched on '+match) debug('Matched on '+match)
# Output/clear buffer when we encounter an end to the stanza # Output/clear buffer when we encounter an end to the stanza
if re.search(end,line) and buffering==True: if re.search(end,line) and buffering==True:
debug('Finished buffering on '+end) debug('Finished buffering on '+end)
if matched: if matched:
# Strip newlines if requrired # Strip newlines if requrired
if cmd.oneline: if cmd.oneline:
print output.replace("\n",'') print output.replace("\n",'')
else: else:
print output print output
buffering=False buffering=False
matched=False matched=False
output='' output=''
else: else:
output='' output=''
buffering=False buffering=False

Loading…
Cancel
Save