Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. from typing import List
  3. import sys
  4. import re
  5. import argparse
  6.  
  7.  
  8. def check(file, name_file, needle, regex, count):
  9. cnt = 0
  10. if name_file != '':
  11. name_file += ':'
  12. for line in file:
  13. line = line.rstrip('\n')
  14. tmp = 1 if regex and re.search(needle, line) or not regex and needle in line else 0
  15. cnt += tmp
  16. if not count and tmp == 1:
  17. if name_file == '':
  18. print(f'{line}')
  19. else:
  20. print(f'{name_file}{line}')
  21. И форматирование навешивал бы в зависимости от каких-нибудь флагов.
  22. if count:
  23. if name_file == '':
  24. print(f'{cnt}')
  25. else:
  26. print(f'{name_file}{cnt}')
  27.  
  28.  
  29. def main(args_str: List[str]):
  30. parser = argparse.ArgumentParser()
  31. parser.add_argument('needle', type=str)
  32. parser.add_argument('files', nargs='*')
  33. parser.add_argument('-E', dest='regex', action='store_true')
  34. parser.add_argument('-c', dest='count', action='store_true')
  35. args = parser.parse_args(args_str)
  36. if not args.files:
  37. check(sys.stdin, '', args.needle, args.regex, args.count)
  38. # REVIEW: Вообще в идеале хотелось бы как-нибудь объеденить две следующие ветки в одну. Потом же меньше страдать придётся :)
  39. elif len(args.files) == 1:
  40. with open(args.files[0], 'r') as in_file:
  41. check(in_file.readlines(), '', args.needle, args.regex, args.count)
  42. else:
  43. for i in args.files:
  44. with open(i, 'r') as in_file:
  45. check(in_file.readlines(), i, args.needle, args.regex, args.count)
  46.  
  47.  
  48. if __name__ == '__main__':
  49. main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement