Skip to content Skip to sidebar Skip to footer

Python Cmd Module Return To Prompt After Catching Exception

I have this code and I'm using python 3: import cmd class myShell(cmd.Cmd): def do_bad(self, arg): raise Exception('something bad happened') if __name__ == '__main__'

Solution 1:

From the code, the functions are called from Cmd.onecmd (even in loop).

You can simply override it:

defonecmd(self, line):
    try:
        returnsuper().onecmd(line)
    except:
        # display error messagereturnFalse# don't stop

The advantage is that you don't stop the command loop.

Solution 2:

well you could override the cmdloop to wrap the original cmdLoop call:

classmyShell(cmd.Cmd):
    defdo_bad(self, arg):
        raise Exception('something bad happened')
    defcmdLoop(self):
       try:
           cmd.Cmd.cmdLoop(self)
       except Exception as e:
           print("recovered from exception {}".format(e))

the wrap will let SystemExit and KeyboardInterrupt pass.

Post a Comment for "Python Cmd Module Return To Prompt After Catching Exception"