Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- from typing import List
- import sys
- import re
- import argparse
- def check(file, name_file, needle, regex, count):
- cnt = 0
- if name_file != '':
- name_file += ':'
- for line in file:
- line = line.rstrip('\n')
- tmp = 1 if regex and re.search(needle, line) or not regex and needle in line else 0
- cnt += tmp
- if not count and tmp == 1:
- if name_file == '':
- print(f'{line}')
- else:
- print(f'{name_file}{line}')
- И форматирование навешивал бы в зависимости от каких-нибудь флагов.
- if count:
- if name_file == '':
- print(f'{cnt}')
- else:
- print(f'{name_file}{cnt}')
- def main(args_str: List[str]):
- parser = argparse.ArgumentParser()
- parser.add_argument('needle', type=str)
- parser.add_argument('files', nargs='*')
- parser.add_argument('-E', dest='regex', action='store_true')
- parser.add_argument('-c', dest='count', action='store_true')
- args = parser.parse_args(args_str)
- if not args.files:
- check(sys.stdin, '', args.needle, args.regex, args.count)
- # REVIEW: Вообще в идеале хотелось бы как-нибудь объеденить две следующие ветки в одну. Потом же меньше страдать придётся :)
- elif len(args.files) == 1:
- with open(args.files[0], 'r') as in_file:
- check(in_file.readlines(), '', args.needle, args.regex, args.count)
- else:
- for i in args.files:
- with open(i, 'r') as in_file:
- check(in_file.readlines(), i, args.needle, args.regex, args.count)
- if __name__ == '__main__':
- main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement