How to always enable debug in a Python Cmd2 App?

590 Views Asked by At

I am using the Cmd2 module in Python (version 1.0.2) to build a command-line interface (CLI).

After I run the program (so that I am inside my custom CLI), if I want debugging to be enabled so that it shows stack traces on errors, I have to manually run "set debug true" from the CLI.

What I want is a way to automatically set the "debug" flag to true every time the CLI is invoked. I know I can pass scripts to the CLI that include setting debug as the first step, but I want interactive sessions to also have this behavior.

Is there any way to change the default value for debug in Cmd2?

1

There are 1 best solutions below

0
On BEST ANSWER

The cmd2 docs about settings say (emphases mine):

Settings

Settings provide a mechanism for a user to control the behavior of a cmd2 based application. A setting is stored in an instance attribute on your subclass of cmd2.Cmd and must also appear in the cmd2.Cmd.settable dictionary. Developers may set default values for these settings and users can modify them at runtime using the set command.

So, to enable the debug setting by default, you just have to set the debug attribute of your cmd2.Cmd object to True. For example, if this is the app:

import cmd2

class App(cmd2.Cmd):
    @cmd2.with_argument_list()
    def do_spam(self, args):
        raise Exception("a sample exception")

you just have to do

app = App()
app.debug = True

Now, if I run the app from the command line, debug will be enabled by default.


Full Python code:

import cmd2


class App(cmd2.Cmd):
    @cmd2.with_argument_list()
    def do_spam(self, args):
        raise Exception("a sample exception")


if __name__ == '__main__':
    import sys

    app = App()
    app.debug = True
    sys.exit(app.cmdloop())

Input:

spam

Output:

Traceback (most recent call last):
  File "[...]\venv\lib\site-packages\cmd2\cmd2.py", line 1646, in onecmd_plus_hooks
    stop = self.onecmd(statement, add_to_history=add_to_history)
  File "[...]\venv\lib\site-packages\cmd2\cmd2.py", line 2075, in onecmd
    stop = func(statement)
  File "[...]\venv\lib\site-packages\cmd2\decorators.py", line 69, in cmd_wrapper
    return func(cmd2_app, parsed_arglist, **kwargs)
  File "[...]/main.py", line 7, in do_spam
    raise Exception("a sample exception")
Exception: a sample exception
EXCEPTION of type 'Exception' occurred with message: 'a sample exception'