Skip to content

Commit 7010fcf

Browse files
committed
[__main__] catch + handle BrokenPipeError raised when executable used with tools like head
1 parent 49090c0 commit 7010fcf

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

lib/fdiff/__main__.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,19 @@
1212

1313

1414
def main(): # pragma: no cover
15-
run(sys.argv[1:])
15+
# try/except block rationale:
16+
# handles "premature" socket closure exception that is
17+
# raised by Python when stdout is piped to tools like
18+
# the `head` executable and socket is closed early
19+
# see: https://docs.python.org/3/library/signal.html#note-on-sigpipe
20+
try:
21+
run(sys.argv[1:])
22+
except BrokenPipeError:
23+
# Python flushes standard streams on exit; redirect remaining output
24+
# to devnull to avoid another BrokenPipeError at shutdown
25+
devnull = os.open(os.devnull, os.O_WRONLY)
26+
os.dup2(devnull, sys.stdout.fileno())
27+
sys.exit(0)
1628

1729

1830
def run(argv):

0 commit comments

Comments
 (0)