cmd
庫是Python的一個內置庫,用于創建交互式命令行應用程序
cmd
庫:import cmd
cmd.Cmd
的類:class MyCLI(cmd.Cmd):
prompt = 'mycli> '
do_
開頭,后跟命令名稱。例如,我們創建一個do_greet
函數來處理greet
命令: def do_greet(self, arg):
print(f"Hello, {arg}!")
help_greet
函數來提供關于greet
命令的幫助信息: def help_greet(self, arg):
print("Usage: greet <name>")
print("Greet the specified person.")
do_exit
函數來處理退出命令: def do_exit(self, arg):
print("Exiting...")
return True
在do_exit
函數中返回True
,以便在用戶輸入exit
時退出程序。
最后,創建一個cmd.Cmd
實例并運行它:
if __name__ == '__main__':
MyCLI().cmdloop()
現在,你可以運行這個程序并使用greet
命令。完整的代碼如下:
import cmd
class MyCLI(cmd.Cmd):
prompt = 'mycli> '
def do_greet(self, arg):
print(f"Hello, {arg}!")
def help_greet(self, arg):
print("Usage: greet <name>")
print("Greet the specified person.")
def do_exit(self, arg):
print("Exiting...")
return True
if __name__ == '__main__':
MyCLI().cmdloop()
這個示例展示了如何使用cmd
庫創建一個簡單的命令行應用程序。你可以根據需要添加更多命令和處理函數。