Oct-07-2019, 05:17 PM
I propose the use of a general function to grab a group of items from a sequence between the first item that satisfies a predicate to the first item that satisfies another predicate. You can easily write a small library for this
from pathlib import Path import re class EmptyGroup(RuntimeError): pass def grab(seq, start, stop): """Grabs items in a sequence starting with the first item for which the predicate start(item) is True until the first item if any for which the predicate stop(item) is True. If no item is grabbed, raise the EmptyGroup exception. """ seq = iter(seq) for x in seq: if start(x): yield x break else: raise EmptyGroup for x in seq: yield x if stop(x): return def all_grabbed(seq, start, stop): """Generate items extracted from a sequence by calling repetively grab(seq, start, stop) until an empty group is returned. """ seq = iter(seq) try: while True: yield from grab(seq, start, stop) except EmptyGroup: pass def main(): start = re.compile(r'^Switch').search stop = re.compile(r'^$').search with Path('paillasse/tmpswitch.log').open() as ifh: for x in all_grabbed(ifh, start, stop): print(repr(x)) if __name__ == '__main__': main()Here is the contents of paillasse/tmpswitch.log
Output:Stack# show version
Switch Ports Model SW Version SW Image
------ ----- ----- ---------- ----------
* 1 30 WS-C3750E-24PD 12.2(46)SE C3750E-UNIVERSAL-M
2 28 WS-C3750E-24PS 12.2(46)SE C3750E-UNIVERSAL-M
3 54 WS-C3750E-48TD 12.2(46)SE C3750E-UNIVERSAL-M
foo bar baz
Switch Ports Model SW Version SW Image
------ ----- ----- ---------- ----------
* 1 30 WS-C3750E-24PD 12.2(46)SE C3750E-UNIVERSAL-M
2 28 WS-C3750E-24PS 12.2(46)SE C3750E-UNIVERSAL-M
3 54 WS-C3750E-48TD 12.2(46)SE C3750E-UNIVERSAL-M
nooo
and here is the program's outputOutput:'Switch Ports Model SW Version SW Image\n'
'------ ----- ----- ---------- ----------\n'
'* 1 30 WS-C3750E-24PD 12.2(46)SE C3750E-UNIVERSAL-M\n'
'2 28 WS-C3750E-24PS 12.2(46)SE C3750E-UNIVERSAL-M\n'
'3 54 WS-C3750E-48TD 12.2(46)SE C3750E-UNIVERSAL-M\n'
'\n'
'Switch Ports Model SW Version SW Image\n'
'------ ----- ----- ---------- ----------\n'
'* 1 30 WS-C3750E-24PD 12.2(46)SE C3750E-UNIVERSAL-M\n'
'2 28 WS-C3750E-24PS 12.2(46)SE C3750E-UNIVERSAL-M\n'
'3 54 WS-C3750E-48TD 12.2(46)SE C3750E-UNIVERSAL-M\n'
'\n'