Skip to content

Instantly share code, notes, and snippets.

@matchaxnb
Last active July 30, 2024 12:01
Show Gist options
  • Select an option

  • Save matchaxnb/6b810a090566bf92c5d4f40a0de72f9e to your computer and use it in GitHub Desktop.

Select an option

Save matchaxnb/6b810a090566bf92c5d4f40a0de72f9e to your computer and use it in GitHub Desktop.
Line and char counter
#!/usr/bin/env python
"""lc: a linecounter. reads stdin and prints advancement in numbers of chars/lines
Usage:
lc -l INTERVAL [--thru]
lc -c INTERVAL [--thru]
Options:
-l INTERVAL output a message every INTERVAL lines [default: 100]
-c INTERVAL output a message every INTERVAL characters [default: 100]
-t --thru passthrough data on stdout and display progress on stderr
"""
import docopt
import sys
MESG_FORMAT = "Output {} lines"
def lc_line(fd, count, thru):
linenum = 0
if thru:
o = sys.stderr
else:
o = sys.stdout
while True:
line = fd.readline()
if thru:
print(line, end='')
if not line:
break
linenum += 1
if linenum % count == 0:
print(MESG_FORMAT.format(linenum), file=o)
print(f"Finished with {linenum} lines", file=o)
def lc_char(fd, count, thru):
charnum = 0
step = count
total_chars = 0
if thru:
o = sys.stderr
else:
o = sys.stdout
while True:
readstuff = fd.read(step)
if thru:
print(readstuff, end='')
total_chars += len(readstuff)
if len(readstuff) < step:
print(f"Nearing end with {total_chars} characters", file=o)
elif not len(readstuff):
break
else:
print(f"Read {total_chars} characters", file=o)
print(f"Finished with {total_chars} characters", file=o)
if __name__ == '__main__':
args = docopt.docopt(__doc__)
if args['-l']:
lc_line(sys.stdin, int(args['-l']), True if args['--thru'] else False)
elif args['-c']:
lc_char(sys.stdin, int(args['-c']), True if args['--thru'] else False)
else:
raise RuntimeError("Wrong arguments")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment