Skip to content

Commit 5cc434b

Browse files
committed
Added broken_pipe_warning attribute of cmd2.Cmd.
It defaults to an empty string. But if a user would like a warning to be printed on a broken pipe error when using poutput() or ppaged(), then they simply set this to the warning they would like printed to sys.stderr.
1 parent c18b2a8 commit 5cc434b

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

cmd2.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,9 @@ def __init__(self, completekey='tab', stdin=None, stdout=None, persistent_histor
11361136
# Used to keep track of whether we are redirecting or piping output
11371137
self.redirecting = False
11381138

1139+
# If this string is non-empty, then this warning message will print if a broken pipe error occurs while printing
1140+
self.broken_pipe_warning = ''
1141+
11391142
# ----- Methods related to presenting output to the user -----
11401143

11411144
@property
@@ -1174,10 +1177,10 @@ def poutput(self, msg, end=os.linesep):
11741177
self.stdout.write(end)
11751178
except BROKEN_PIPE_ERROR:
11761179
# This occurs if a command's output is being piped to another process and that process closes before the
1177-
# command is finished. We intentionally don't print a warning message here since we know that stdout
1178-
# will be restored by the _restore_output() method. If you would like your application to print a
1179-
# warning message, then override this method.
1180-
pass
1180+
# command is finished. If you would like your application to print a warning message, then set the
1181+
# broken_pipe_warning attribute to the message you want printed.
1182+
if self.broken_pipe_warning:
1183+
sys.stderr.write(self.broken_pipe_warning)
11811184

11821185
def perror(self, errmsg, exception_type=None, traceback_war=True):
11831186
""" Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists.
@@ -1254,10 +1257,10 @@ def ppaged(self, msg, end=os.linesep):
12541257
self.stdout.write(msg_str)
12551258
except BROKEN_PIPE_ERROR:
12561259
# This occurs if a command's output is being piped to another process and that process closes before the
1257-
# command is finished. We intentionally don't print a warning message here since we know that stdout
1258-
# will be restored by the _restore_output() method. If you would like your application to print a
1259-
# warning message, then override this method.
1260-
pass
1260+
# command is finished. If you would like your application to print a warning message, then set the
1261+
# broken_pipe_warning attribute to the message you want printed.
1262+
if self.broken_pipe_warning:
1263+
sys.stderr.write(self.broken_pipe_warning)
12611264

12621265
def colorize(self, val, color):
12631266
"""Given a string (``val``), returns that string wrapped in UNIX-style

0 commit comments

Comments
 (0)