--- orig/urlescape
+++ mod/urlescape
@@ -89,9 +89,10 @@
             if line_based:
                 if line[-1] == '\n':
                     line = line[:-1]
-            sys.stdout.write(function(line))
+            write(function(line))
             if line_based:
-                sys.stdout.write('\n')
+                write('\n')
+
     sys.exit(os.EX_OK)
 
 class UsageAction(argparse.Action):
@@ -99,6 +100,20 @@
         parser.print_usage()
         parser.exit(os.EX_USAGE)
 
+def exit_brokenpipe():
+    # redirect output stream to /dev/null avoid additinal BrokenPipeError
+    # in TextIOWrapper during cleanup
+    devnull = os.open(os.devnull, os.O_WRONLY)
+    os.dup2(devnull, sys.stdout.fileno())
+
+    sys.exit(os.EX_IOERR)
+
+def write(string):
+    try:
+        sys.stdout.write(string)
+    except BrokenPipeError:
+        exit_brokenpipe()
+
 def error(msg):
     sys.stderr.write("{prog}: {message}\n".format(
         prog=os.path.basename(sys.argv[0]),
@@ -111,3 +126,10 @@
         main()
     except KeyboardInterrupt:
         sys.exit(128 + signal.SIGINT)
+    finally:
+        try:
+            sys.stdout.flush()
+        except BrokenPipeError:
+            exit_brokenpipe()
+
+    sys.exit(os.EX_OK)
