summaryrefslogtreecommitdiff
path: root/cmd2/cmd2.py
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2018-06-06 23:35:28 -0400
committerTodd Leonhardt <todd.leonhardt@gmail.com>2018-06-06 23:35:28 -0400
commite7367b692bad892f27c0dd7ad04e6aa3c9f56230 (patch)
tree8e318c476b33257671e2053c9f4684cfe8a70fe8 /cmd2/cmd2.py
parent794414745f7c28c4c96300117ce9a57c38d4d5b5 (diff)
downloadcmd2-git-e7367b692bad892f27c0dd7ad04e6aa3c9f56230.tar.gz
Fixed a couple potential crashes on opening files
Fixed crashes that occur when attempting to open a file in a non-existent directory or a when the filename is too long. Specifically fixed this when redirecting output to a file and when saving a transcript based on the history. Also added a couple unit tests related to the fixes.
Diffstat (limited to 'cmd2/cmd2.py')
-rw-r--r--cmd2/cmd2.py29
1 files changed, 18 insertions, 11 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 2d8766f4..3f000318 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -1696,7 +1696,7 @@ class Cmd(cmd.Cmd):
if self.timing:
self.pfeedback('Elapsed: %s' % str(datetime.datetime.now() - timestart))
finally:
- if self.allow_redirection:
+ if self.allow_redirection and self.redirecting:
self._restore_output(statement)
except EmptyStatement:
pass
@@ -1840,7 +1840,11 @@ class Cmd(cmd.Cmd):
# REDIRECTION_APPEND or REDIRECTION_OUTPUT
if statement.output == constants.REDIRECTION_APPEND:
mode = 'a'
- sys.stdout = self.stdout = open(os.path.expanduser(statement.output_to), mode)
+ try:
+ sys.stdout = self.stdout = open(os.path.expanduser(statement.output_to), mode)
+ except (FileNotFoundError, OSError) as ex:
+ self.perror('Not Redirecting because - {}'.format(ex), traceback_war=False)
+ self.redirecting = False
else:
# going to a paste buffer
sys.stdout = self.stdout = tempfile.TemporaryFile(mode="w+")
@@ -2878,16 +2882,19 @@ a..b, a:b, a:, ..b items by indices (inclusive)
self.echo = saved_echo
# finally, we can write the transcript out to the file
- with open(transcript_file, 'w') as fout:
- fout.write(transcript)
-
- # and let the user know what we did
- if len(history) > 1:
- plural = 'commands and their outputs'
+ try:
+ with open(transcript_file, 'w') as fout:
+ fout.write(transcript)
+ except (FileNotFoundError, OSError) as ex:
+ self.perror('Failed to save transcript: {}'.format(ex), traceback_war=False)
else:
- plural = 'command and its output'
- msg = '{} {} saved to transcript file {!r}'
- self.pfeedback(msg.format(len(history), plural, transcript_file))
+ # and let the user know what we did
+ if len(history) > 1:
+ plural = 'commands and their outputs'
+ else:
+ plural = 'command and its output'
+ msg = '{} {} saved to transcript file {!r}'
+ self.pfeedback(msg.format(len(history), plural, transcript_file))
@with_argument_list
def do_edit(self, arglist):