如何在 python raw_input 中使用 tab 键补全?
本文介绍了如何在 python raw_input 中使用 tab 键补全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
如何在 python raw_input 中使用 tab 键补全?
解决方案
拋磚
用 readline, 以下是一個簡單的小範例:
import readline
CMD = ['foo1', 'foo2', 'bar1', 'bar2', 'exit']
def completer(text, state):
options = [cmd for cmd in CMD if cmd.startswith(text)]
if state < len(options):
return options[state]
else:
return None
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
while True:
cmd = raw_input('==> ')
if cmd=='exit':
break
print(cmd)
測試:
==> <TAB><TAB>
bar1 bar2 exit foo1 foo2
==> b<TAB>
==> bar
==> bar<TAB><TAB>
bar1 bar2
==> bar1
bar1
==> exit
引玉
其實我沒有完全理解 completer 的作用原理, 尤其是 state
的部分, 希望有高手可以闡釋, 十分感謝!
我回答過的問題: Python-QA
这篇关于如何在 python raw_input 中使用 tab 键补全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文