Browse Source

added proper args, help message with argparse, added oneline, commented things

master
Ben Savage 7 years ago
parent
commit
187a366fb2
  1. 53
      stanza

53
stanza

@ -2,41 +2,72 @@
import sys import sys
import re import re
import argparse
from pprint import *
# Debug function
# Setup vars
buffering=False buffering=False
matched=False matched=False
output='' output=''
start=sys.argv[1]
match=sys.argv[2]
end=sys.argv[3]
if len(sys.argv) == 4: # Setup/parse arguments
handle=sys.stdin parser = argparse.ArgumentParser(description='Output lines based on complex criteria')
elif len(sys.argv) == 5: parser.add_argument('start',help='Regex to start buffering on')
handle=open(sys.argv[4]) parser.add_argument('end',help='Regex to close a stanza and output buffer')
parser.add_argument('-1','--oneline', help='Output each stanza on one line',action='store_true',dest='oneline', default=False)
parser.add_argument('-d','--debug', help='Debug',action='store_true', default=False)
parser.add_argument('-m','--match',help='Regex to indicate a valid/desired stanza to output',default='.', action='store',metavar="/r/")
parser.add_argument('-f','--file',help='File to operate on, defaults to stdin',metavar='FILE',required=False, default=None,dest='filename',action='store')
args = parser.parse_known_args(sys.argv[1:])
# Move namespace into separate var
cmd=args[0]
# Set up positional args
start=cmd.start
match=cmd.match
end=cmd.end
def debug(line): def debug(line):
# print line if cmd.debug:
pass print line
debug(pformat(args))
# Set up the file handle, <file> or stdin
if cmd.filename:
handle=open(cmd.filename)
else:
handle=sys.stdin
# Go over the handle, line by line
for line in handle: for line in handle:
# Start buffering if we hit the start regex
if re.search(start,line): if re.search(start,line):
buffering=True buffering=True
debug('Started buffering on '+start) debug('Started buffering on '+start)
# Continue buffering if we've already started
if buffering: if buffering:
output+=line output+=line
if re.search(match,line): # If a line in the stanza matches, we output the stanza
if buffering and re.search(match,line):
matched=True matched=True
debug('Matched on '+match) debug('Matched on '+match)
if re.search(end,line): # Output/clear buffer when we encounter an end to the stanza
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
if cmd.oneline:
print output.replace("\n",'')
else:
print output print output
buffering=False buffering=False
matched=False matched=False
output=''
else: else:
output='' output=''
buffering=False buffering=False

Loading…
Cancel
Save