File: class/Workbook/Examples/Lecture10/unmore2.py

#!/usr/local/bin/python
# unpack result of "more x y z > f"
# usage: "unmore2.py f" or "unmore2.py < f"
# packages unpacking logic as an importable function

import sys
marker = ':'*14

def unmore(input):
    output = sys.stdout
    while 1:
        line = input.readline()
        if not line:                        # end of file?
            break
        elif line[:14] != marker:              # text line?
            output.write(line)
        else:                                  # file prefix
            fname = input.readline()[:-1]      # strip eoln
            print 'creating', `fname`
            output = open(fname, "w")          # next output
            if input.readline()[:14] != marker:
                print "OOPS!"; sys.exit(1)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        unmore(sys.stdin)                  # unmore2.py < f
    else:
        unmore(open(sys.argv[1], 'r'))     # unmore2.py f
    print 'Done.'



[Home page] Books Code Blog Python Author Train Find ©M.Lutz