Program tail

From Software Engineers Wiki
Jump to: navigation, search

Implement tail program that shows last part of files.

Answer : python

import sys, getopt

def usage():
        "Show usage of this program."
        print("Usage: tail [OPTIONS] <filename>")
        print("-n, --line=K: output the last K lines, instead of the last 10.")

def tail(f, lines):
        lastLines = []
        linesInBuf = 0
        while True:
                str = f.readline()
                if len(str) == 0:
                        break;
                if linesInBuf == lines:
                        del lastLines[0]
                        linesInBuf -= 1
                lastLines.append(str)
                linesInBuf += 1

        for i in range(linesInBuf):
                sys.stdout.write(lastLines[i])

def main():
        # parse parameters
        paramLines = 10
        paramFileName = None
        try:
                opts, args = getopt.getopt(sys.argv[1:], "n:", [ "lines=" ])

                if (len(args) == 0):
                        usage()
                        sys.exit(1)
                paramFileName = args[0]

                for opt, optArg in opts:
                        if opt in ("-n", "--lines"):
                                paramLines = int(optArg)

        except getopt.GetoptError as e:
                print(str(e))
                sys.exit(1)

        f = None
        try:
                f = open(paramFileName, "r")
                tail(f, paramLines)
                f.close()
        except IOError as e:
                print(str(e))
        except OSError as e:
                print(str(e))
                # print(sys.exc_info()[0])

main()
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox