增强Python cmd模块的“帮助”输出

1 投票
1 回答
677 浏览
提问于 2025-04-18 14:12

我正在使用Python的cmd模块来为一个应用程序创建一个自定义的交互式提示符。目前,当我在提示符下输入help时,它会自动显示我自定义命令的列表,比如:

[myPromt] help

Documented commands (type help <topic>):
========================================
cmd1 cmd2 cmd3

我想在这个列表中添加一些文字,解释在提示符下可以使用的快捷键,比如:

[myPromt] help

Documented commands (type help <topic>):
========================================
cmd1 cmd2 cmd3

(use Ctrl+l to clear screen, Ctrl+a to move cursor to line start, Ctrl+e to move cursor to line end)

有没有人知道怎么修改在输入help命令时显示的默认文本?

1 个回答

1

你可以试试使用doc_header属性

import cmd

class MyCmd(cmd.Cmd):
    def do_cmd1(self): pass
    def do_cmd2(self): pass
    def do_cmd3(self): pass

d = MyCmd()
d.doc_header = '(use Ctrl+l to clear screen, Ctrl+a ...)'  # <---
d.cmdloop()

示例输出:

(Cmd) ?

(use Ctrl+l to clear screen, Ctrl+a ...)
========================================
help

Undocumented commands:
======================
cmd1  cmd2  cmd3

如果你想把自定义的信息放在正常帮助信息之后,可以使用do_help

import cmd

class MyCmd(cmd.Cmd):
    def do_cmd1(self): pass
    def do_cmd2(self): pass
    def do_cmd3(self): pass
    def do_help(self, *args):
        cmd.Cmd.do_help(self, *args)
        print 'use Ctrl+l to clear screen, Ctrl+a ...)'

d = MyCmd()
d.cmdloop()

输出:

(Cmd) ?

Undocumented commands:
======================
cmd1  cmd2  cmd3  help

use Ctrl+l to clear screen, Ctrl+a ...)

撰写回答