用readline.parse_and_bind("tab:complete")可以弄到命令名自动补全,可是好像路径名不行哦,比如/hom后按TAB键不能变成/home,要怎么设才能达到这个目的呢?
wolfg 回复于:2005-09-21 10:33:52
rlcompleter只对python的模块名起作用吧
linux_23 回复于:2005-09-21 10:47:30
那么怎么让路径和文件名补齐呢?
wolfg 回复于:2005-09-21 11:40:09
引用:原帖由 "linux_23"]那么怎么让路径和文件名补齐呢? 发表:
能说的具体些吗?你是想在你的python程序中让用户输入时可以自动补全吗?
linux_23 回复于:2005-09-21 13:39:41
比如说吧,我想建立一个控制台交互式的程序。用户可以在控制台中输入我定义的命令和参数,来控制程序做一些事
假设我定义有这么一条命令:openfile /path/to/file
现在利用readline.parse_and_bind("tab:complete")可以做到自动补齐openfile的命令名(比如我输入op(TAB)就会显示openfile)。但是路径和文件名无法补齐(比如说/ho(TAB)就没法补齐成/home),用cmd模块的效果也是一样的。
我的问题就是如何在用户输入时做到可以按TAB自动补齐路径或者当前路径中的文件名?单单用readline或者cmd模块可以做到吗?
xichen 回复于:2005-09-21 14:32:21
这个还不懂,抱歉。
ygao2004 回复于:2005-09-22 20:03:31
试一试:Ipython
可满足你的要求。
linux_23 回复于:2005-09-26 09:09:48
呵呵,我把cmd模块的complete函数改写覆盖了一下,现在凑合用了。
wolfg 回复于:2005-09-26 10:05:56
引用:原帖由 "linux_23"]呵呵,我把cmd模块的complete函数改写覆盖了一下,现在凑合用了。 发表:
怎么实现的?能否与大家分享?
linux_23 回复于:2005-09-26 13:59:24
继承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
xichen 回复于:2005-09-26 15:46:03
精彩
|