如何始终在 Python Cmd2 应用程序中启用调试?

How to always enable debug in a Python Cmd2 App?

我正在使用 Python(版本 1.0.2)中的 Cmd2 模块来构建命令行界面 (CLI)。

在我 运行 程序之后(这样我就在我的自定义 CLI 中),如果我想启用调试以便它显示错误的堆栈跟踪,我必须手动 运行从 CLI 中“设置调试为真”。

我想要的是一种在每次调用 CLI 时自动将“调试”标志设置为 true 的方法。我知道我可以将脚本传递给 CLI,其中包括将调试设置作为第一步,但我希望交互式会话也具有此行为。

有什么方法可以更改 Cmd2 中调试的默认值吗?

cmd2 docs about settings 说(强调我的):

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.

因此,要默认启用 debug setting,您只需将 cmd2.Cmd 对象的 debug 属性设置为 True。例如,如果这是应用程序:

import cmd2

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

你只需要做

app = App()
app.debug = True

现在,如果我从命令行 运行 应用程序,debug 将默认启用。


完整 Python 代码:

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())

输入:

spam

输出:

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'