zoukankan      html  css  js  c++  java
  • Python cmd库的简易使用

    简单记录一下,竟然这么简单的方法就能在 python 里面实现一个简单的交互式命令行以前从来没有尝试过。

    上一个完整的例子:

    import cmd
    import os
    import readline

    readline.parse_and_bind('tab: complete')
    class CLI(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = "Miller2 > " # define command prompt def do_dir(self, arg): if not arg: self.help_dir() elif os.path.exists(arg): print" ".join(os.listdir(arg)) else: print "No such pathexists." def help_dir(self): print "syntax: dir path -- displaya list of files and directories" def do_quit(self, arg): return True def help_quit(self): print "syntax: quit -- terminatesthe application" # define the shortcuts do_q = do_quit if __name__ == "__main__": cli = CLI() cli.cmdloop(intro="welcome to axiba")

    使用 readline 来实现了命令交互 tab 提示补全的功能。 然后是 CLI 类继承了 cmd.Cmd。

    self.prompt 用于指定提示符样式。

    交互命令行的规则定义就是 do_cmd 就可以在运行的使用 cmd 命令。如果出错可以调用自己定义的数据。

    backup 一份常用函数,可以根据这些钩子函数来达到自己想要的交互效果:

    (1)cmdloop():类似与Tkinter的mainloop,运行Cmd解析器;
    
    (2)onecmd(str):读取输入,并进行处理,通常不需要重载该函数,而是使用更加具体的do_command来执行特定的命令;
    
    (3)emptyline():当输入空行时调用该方法;
    
    (4)default(line):当无法识别输入的command时调用该方法;
    
    (5)completedefault(text,line,begidx,endidx):如果不存在针对的complete_*()方法,那么会调用该函数,该函数主要是用于tab补充,且只能在linux下使用。
    
    (6)precmd(line):命令line解析之前被调用该方法;
    
    (7)postcmd(stop,line):命令line解析之后被调用该方法;
    
    (8)preloop():cmdloop()运行之前调用该方法;
    
    (9)postloop():cmdloop()退出之后调用该方法;
    
    (10)help_command():对command命令的说明,其中command为可变字符

    reference:

    https://www.cnblogs.com/r00tuser/p/7515136.html  简单认识python cmd模块

  • 相关阅读:
    51keil编译器printf函数
    asp.net里登陆记住密码
    Asp.net GridView分页
    DataTable拆分分页
    ASP.NET MVC 窗体身份验证及角色权限治理示例
    asp.net获取IP地址
    Asp.net Ajax框架教程
    将页面的ViewState放在Session
    20个Jquery表单插件
    前端下载图片的N种方法
  • 原文地址:https://www.cnblogs.com/piperck/p/8480198.html
Copyright © 2011-2022 走看看