python cmd2 using the first command that contains a hyphen

83 Views Asked by At

Using CMD2 CLI I want to create a command that has a hyphen in the first command.

def do_command_something(self, args):
   print("command-something")

I want it to work as below

cmd> command-something
command-something

I have been looking for a while and can not come up with a way within the CMD2 framework to make this work.

1

There are 1 best solutions below

0
On BEST ANSWER

Hyphen is not a valid character as an identifier in Python, so you cannot name a method with it directly in the class definition.

Instead, define the do method under a different name first, and then use setattr on the class object to give the method the desired name with a hyphen. You can delete the original name after that if you want:

import cmd2

class App(cmd2.Cmd):
    def do_command_something(self, args):
        print("command-something")

setattr(App, 'do_command-something', App.do_command_something)
del App.do_command_something
App().cmdloop()

Demo: https://replit.com/@blhsing1/HealthyConcernedRotation

Test run:

(Cmd) command-something
command-something
(Cmd) command_something
command_something is not a recognized command, alias, or macro
(Cmd)