- 论坛徽章:
- 0
|
如何在raw_input输入时自动补全路径名?
继承Cmd类,然后覆盖complete函数
def complete(self, text, state):
"""Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command>; to get list of completions.
"""
if state == 0:
import readline
#重新设置过滤字符串。把/设成分割符。
readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>;?')
origline = readline.get_line_buffer()
line = origline.lstrip()
stripped = len(origline) - len(line)
begidx = readline.get_begidx() - stripped
endidx = readline.get_endidx() - stripped
if begidx>;0:
cmd, args, foo = self.parseline(line)
#添加对有‘/’的路径和文件的补全
if r"/" in text:
compfunc = self.path_matches
elif cmd == '':
compfunc = self.completedefault
else:
try:
compfunc = getattr(self, 'complete_' + cmd)
except AttributeError:
compfunc = self.completedefault
else:
compfunc = self.completenames
self.completion_matches = compfunc(text, line, begidx, endidx)
try:
return self.completion_matches[state]
except IndexError:
return None
再添加path_matches函数来补齐路径
def path_matches(self, text, *ignored):
import os
at = text.rfind('/')
if at <>; 0:
path = text[0]
filist = os.listdir(path)
else:
path = ''
filist = os.listdir('/')
f = text[at+1:]
matches = []
n=len(f)
for word in filist:
if word[] == f:
matches.append("%s/%s" % (path, word))
return matches |
|