Skip to content

Commit c3f16b5

Browse files
ntrrgcmildsunrise
authored andcommitted
Handle KeyboardInterrupt quietly, fix signal return codes
This is a continuation of #8. The previous patch handled BrokenPipeError, this one makes it so that KeyboardInterrupt is also handled. This is relevant when pressing ^C on very large outputs (e.g. big files with --rows 999999). If such use of ^C occurs while in a pager, broken pipe errors were also printed by the Python exit error handler. This patch makes it so that both BrokenPipeError and KeyboardInterrupt exit quietly. As a drive-by fix, I realized that the exit codes were not following the convention typically used e.g. by shells. The new code follows such convention.
1 parent a999908 commit c3f16b5

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

mp4parser.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Core parsing logic
44
'''
55

6-
from errno import EPIPE
6+
import os
77
import sys
88
import mmap
99
import itertools
@@ -252,7 +252,7 @@ def subparser(self, n: int):
252252
def handle_errors(self):
253253
try:
254254
with self: yield self
255-
except BrokenPipeError:
255+
except (BrokenPipeError, KeyboardInterrupt) as err:
256256
# All of this is necessary so that no exceptions are printed when
257257
# the user pipes `mp4parser --rows 1000 large_file.mp4 | less` and
258258
# quits with 'q' before getting close to the end of the file.
@@ -271,7 +271,15 @@ def handle_errors(self):
271271
sys.stdout.close()
272272
except BrokenPipeError:
273273
pass
274-
raise SystemExit(EPIPE)
274+
if os.name == "posix":
275+
from signal import SIGINT, SIGPIPE
276+
else:
277+
# If we're in Windows or any other platform without signal ids,
278+
# use the Linux x86 signal ids, just to give something helpful.
279+
SIGINT, SIGPIPE = 2, 13
280+
# Standard exit codes are 128 + signal id.
281+
exit_code = 128 + (SIGINT if isinstance(err, KeyboardInterrupt) else SIGPIPE)
282+
raise SystemExit(exit_code)
275283
except Exception as e:
276284
print_error(e, self.prefix)
277285
if max_dump and self.buffer:

0 commit comments

Comments
 (0)