`
gumuzhiyu
  • 浏览: 35599 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

python cat

 
阅读更多
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import sys, os
import argparse
import re


def showprintings(f,endchar,showNum=False):
    max_len = 4096
    num = 0
    prog = re.compile('\t')
    prog2 = re.compile('\r\n')

    if not os.path.isfile(f):
        print("{}: not a file".format(f))

    try:
        with open(f, "rb") as fp:
            for line in iter(lambda: fp.readline(max_len), b''):
                line = line.decode()
                if showNum == True:
                    num += 1
                    if endchar == 'Num':
                        if line != '\r\n':
                            print("{} {}".format(num, line), end='')
                        else:
                            print('')
                    else:
                        print("{} {}".format(num, line), end='')
                else:
                    if endchar == "$":
                        line = prog2.sub('$', line)
                        print("{}".format(line), end='\n')
                    elif endchar == "T":
                        line = prog.sub('^I', line)
                        line = line[:-2]
                        print("{}".format(line), end='\n')
                    else:
                        print("{}".format(line), end='')
    except Exception as e:
        print(e)


def main():
    usage = 'cat - concatenate files and print on the standard output'
    parser = argparse.ArgumentParser(usage) 
    parser.add_argument('-n', action='store_true', default=False, help='number all output lines')
    parser.add_argument('-b', action='store_true', default=False, help='number nonempty output lines')
    parser.add_argument('-v', action='store_true', default=False, help='use ^ and M- notation, except for LFD and TAB')
    parser.add_argument('-E', action='store_true', default=False, help='display $ at end of each line')
    parser.add_argument('-T', action='store_true', default=False, help='display TAB characters as ^I')
    parser.add_argument('-t', action='store_true', default=False, help='equivalent to -vT')


    parser.add_argument("x", type=str, help="File1")

    args = parser.parse_args()
    if args.v:
        showprintings(args.x, '', False)
    elif args.E:
        showprintings(args.x, '$', False)
    elif args.b:
        showprintings(args.x, 'Num', True)
    elif args.n:
        showprintings(args.x, '', True)
    elif args.T or args.t:
        showprintings(args.x, 'T', False)
    else:
        print(parser.print_help())


if __name__ == '__main__':
    main()

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics