linux终端命令自动补全功能咋实现

用python 2写了个简单粗暴的demo,仅限linux环境:# coding:utf8import sys, tty, termios, osimport urllib2# 生成文本(单词、句子)列表def GenWordList():\tdata = https://www.zhihu.com/api/v4/questions/35359910/urllib2.urlopen(/u0026#39;http://cn.bing.com/robots.txt/u0026#39;).read()/twordList = list(set(data.split(/u0026#39;//r//u0026#39;)))/twordList.sort()/treturn wordList/t# 去除第一行空白wordList = GenWordList()# 根据关键字key获取关联的候选词列表def getCandidates(key):/treturn (word for word in wordList if word.lower().startswith(key.lower()))# 输入的关键字发生变化时,刷新界面def onTextChanged(text):/tos.system(/u0026#39;clear/u0026#39;)/tprint text/tprint /u0026#39;//u0026#39;.join()# 等待键盘按键def waitForAnyKey():/tfd = sys.stdin.fileno()/tbackup = termios.tcgetattr(fd)/ttry:/t/ttty.setraw(fd)/t/treturn ord(sys.stdin.read(1))/tfinally:/t/ttermios.tcsetattr(fd, termios.TCSADRAIN, backup)# 主循环def eventLoop():/ttext = /u0026#39;/u0026#39;/twhile True:/t/tkeyCode = waitForAnyKey()/t/t/t/tif keyCode == 3:/t# Ctrl+C退出/t/t/tbreak/t/tif keyCode == 127:/t# Backspace删除一个字符/t/t/tif len(text) == 0:/t/t/t/tcontinue/t/t/ttext = text/t/t/tonTextChanged(text)/t/telif keyCode /u0026gt;= 32 and keyCode /u0026lt;= 126:/t# 可打印字符/t/t/ttext += chr(keyCode)/t/t/tonTextChanged(text)/t/tos.system(/u0026#39;clear/u0026#39;)eventLoop()运行效果: 【linux终端命令自动补全功能咋实现】 linux终端命令自动补全功能咋实现


■网友
翻翻zsh源码?感觉zsh自动补全/纠正简直逆天
■网友
先收集corpus。然后坐前缀匹配……
■网友
去看bash的代码你就知道了?


    推荐阅读