2020年9月25日 星期五

[ Python 常見問題 ] Aliases for commands with Python cmd module

 Source From Here

Question
How can I create an alias for a command in a line-oriented command interpreter implemented using the cmd module?

To create a command, I must implement the do_cmd method. But I have commands with long names (like constraint) and I want to provide aliases (in fact, shortcuts) for these commands (like co). How can I do that? One possibility that came to my mind is to implement the do_alias (like do_co) method and just calling do_cmd (do_constraint) in this method. But this brings me new commands in the help of the CLI.

Is there any other way to achieve this? Or may be is there a way to hide commands from the help output?

HowTo
You can overwrite the default method and search for a suitable command handler (as already suggested by Brian):
  1. import cmd  
  2. import sys  
  3.   
  4. class WithAliasCmd(cmd.Cmd):  
  5.     def do_long_cmd_name(self, arg):  
  6.         print("Hello world!")  
  7.   
  8.     def default(self, line):  
  9.         cmd, arg, line = self.parseline(line)  
  10.         func = [getattr(self, n) for n in self.get_names() if n.startswith('do_' + cmd)]  
  11.         if func: # maybe check if exactly one or more elements, and tell the user  
  12.             func[0](arg)  
  13.         elif cmd == "hello": # "hello" is an alias for command long_cmd_name  
  14.             return self.do_long_cmd_name(arg)  
  15.   
  16.     def do_bye(self, arg):  
  17.         print("Bye")  
  18.         return True  
  19.   
  20.   
  21. if __name__ == '__main__':  
  22.     WithAliasCmd().cmdloop()  
Execution output:
C:\tmp> python cmd_alias.py
(Cmd) ?

Documented commands (type help <topic>):
========================================
help

Undocumented commands:
======================
bye long_cmd_name


(Cmd) long_cmd_name
Hello world!
(Cmd) hello
Hello world!


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...