-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount
executable file
·109 lines (83 loc) · 2.28 KB
/
count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
#
# count
# counts lines in the standard input, or the given files
#
# desc:
# - equivalent to wc -l (different output format if files given)
# - 5x slower than C version (wc -l) in measurements, python-3.9.5
#
# status:
# - experiment to determine python's speed with simple IO loop + counter
# - not very fast! using mmap supposedly doubles, but still... unimpressive
#
# scott@smemsh.net
# https://github.com/smemsh/utilpy/
# https://spdx.org/licenses/GPL-2.0
#
##############################################################################
"""
count lines in files
counts number of lines on stdin, or:
if args supplied, gives "filename: count" for each
"""
from sys import argv, stdin
from os import environ
###
def usagex():
print("{}:".format(invname), __doc__.strip())
quit()
###
def countlines(file):
count = 0
for _ in file:
count += 1
return count
###
def main():
no_more_options = False
if (nargs == 0):
print(countlines(stdin.buffer))
else:
files = []
for arg in args:
if (no_more_options):
files.append(arg); continue
elif (arg == '--'):
no_more_options = True; continue
elif (arg == '-h' or arg == '--help'):
usagex()
elif (arg[0] == '-'):
print("{}: opterr".format(invname)); quit()
else:
files.append(arg)
no_more_options = True
for file in files:
try:
with open(file, "rb") as f:
count = countlines(f)
print('{}: {}'.format(file, count))
except FileNotFoundError:
print("{}: {}: nsfod".format(invname, file))
raise
except:
print("{}: unhandled".format(invname))
raise
###
if (__name__ == "__main__"):
try:
if (bool(environ['DEBUG'])):
debug = True
import pdb
from pprint import pprint as pp
pp('debug-mode-enabled')
pdb.set_trace()
else:
raise KeyError
except KeyError:
debug = False
invname = argv[0]
args = argv[1:]
nargs = len(args)
main()
#