Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python cmd module return to prompt after catching exception

Tags:

python

cmd

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__':
    sh = myShell()
    sh.cmdloop()

and I want to return to the shell-prompt after the exception was thrown. How to do that?

like image 768
thengineer Avatar asked Mar 06 '23 23:03

thengineer


1 Answers

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

You can simply override it:

def onecmd(self, line):
    try:
        return super().onecmd(line)
    except:
        # display error message
        return False # don't stop

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

like image 122
Michael Doubez Avatar answered Mar 15 '23 08:03

Michael Doubez