From 7c78350f8903f162e5f70ee147c0e97cb1ed5181 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Lapeyre?= Date: Fri, 29 Jun 2018 22:52:03 +0200 Subject: [PATCH] Add dynamic commands to cmd.Cmd --- Lib/cmd.py | 2 +- Lib/test/test_cmd.py | 37 +++++++++++++++++++ .../2018-06-29-22-54-57.bpo-28657.kFuljC.rst | 2 + 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2018-06-29-22-54-57.bpo-28657.kFuljC.rst diff --git a/Lib/cmd.py b/Lib/cmd.py index 859e91096d8f57d..a96a4c514fbd8de 100644 --- a/Lib/cmd.py +++ b/Lib/cmd.py @@ -281,7 +281,7 @@ def complete(self, text, state): def get_names(self): # This method used to pull in base class attributes # at a time dir() didn't do it yet. - return dir(self.__class__) + return dir(self) def complete_help(self, *args): commands = set(self.completenames(*args)) diff --git a/Lib/test/test_cmd.py b/Lib/test/test_cmd.py index 96e0c30da328cfc..42a2416010a0b14 100644 --- a/Lib/test/test_cmd.py +++ b/Lib/test/test_cmd.py @@ -218,6 +218,43 @@ def test_input_reset_at_EOF(self): "(Cmd) \n" "(Cmd) *** Unknown syntax: EOF\n")) + def test_dynamic_commands(self): + input = io.StringIO("help") + output = io.StringIO() + cmd = self.simplecmd(stdin=input, stdout=output) + cmd.use_rawinput = False + cmd.do_echo = lambda line: print(line) + cmd.cmdloop() + self.assertMultiLineEqual(output.getvalue(), + ("(Cmd) \n" + "Documented commands (type help ):\n" + "========================================\n" + "help\n" + "\n" + "Undocumented commands:\n" + "======================\n" + "EOF echo print\n" + "\n" + "(Cmd) ")) + + def test_dynamic_documentation(self): + input = io.StringIO("help") + output = io.StringIO() + cmd = self.simplecmd(stdin=input, stdout=output) + cmd.use_rawinput = False + cmd.help_print = lambda: print("documented") + cmd.cmdloop() + self.assertMultiLineEqual(output.getvalue(), + ("(Cmd) \n" + "Documented commands (type help ):\n" + "========================================\n" + "help print\n" + "\n" + "Undocumented commands:\n" + "======================\n" + "EOF\n" + "\n" + "(Cmd) ")) def test_main(verbose=None): from test import test_cmd diff --git a/Misc/NEWS.d/next/Library/2018-06-29-22-54-57.bpo-28657.kFuljC.rst b/Misc/NEWS.d/next/Library/2018-06-29-22-54-57.bpo-28657.kFuljC.rst new file mode 100644 index 000000000000000..eeba366ebe4eda4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-06-29-22-54-57.bpo-28657.kFuljC.rst @@ -0,0 +1,2 @@ +cmd.Cmd now support commands added directly to instances. Patch by Rémi +Lapeyre.