-
Notifications
You must be signed in to change notification settings - Fork 4
/
chomp
executable file
·47 lines (36 loc) · 1.04 KB
/
chomp
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
#!/usr/bin/env python3
import os
import sys
# couldn't figure out how to make fileinput not be line-oriented (pity)
# not quite the same as ruby's chomp ("hello\n\r" => "hello")
def chomp(handle, chunk_size=8092):
while True:
chunk = handle.read(chunk_size)
if len(chunk) < chunk_size:
break
sys.stdout.write(chunk)
sys.stdout.write(chunk.rstrip('\r\n'))
def chomp_handles(handles):
for handle in handles:
chomp(handle)
def run(filenames):
handles = []
for name in filenames:
if name == '-':
handles.append(sys.stdin)
else:
handles.append(open(name, 'r'))
chomp_handles(handles)
if __name__ == '__main__':
filenames = sys.argv[1:]
if not filenames:
filenames = ['-']
basename = os.path.basename(sys.argv[0])
try:
run(filenames)
except KeyboardInterrupt:
print()
sys.exit(130)
except IOError as e:
sys.stderr.write("%s: %s: %s\n" % (basename, e.filename, e.strerror))
sys.exit(1)