[英]Python: how can I make cmd.Cmd() honor hyphens in filenames?
如何在文件名中使cmd.Cmd()接受连字符? 如果我在测试完成时使用下划线替换连字符,则此代码将正常工作。
我们可以通过按两次start
命令来看到问题。
$ ./test-cmd.py
(Cmd) start <tab><tab> ## good, we see all completions
far foo i-09349 i-5sjdk i-far i-foo z-foo
(Cmd) start f <tab><tab> ## good, we see completions that start with "f"
far foo
(Cmd) start i- <tab><tab> ## now we see all completions, not just "i-"
far foo i-09349 i-5sjdk i-far i-foo z-foo
码:
import cmd
#-----------------------------------------------------------------------
def D(s):
"""write to a debug file so as not to disturb tab completion output"""
dbgfd.write(str(s)+'\n')
dbgfd.flush()
dbgfd=open('cmd.dbg','a')
#-----------------------------------------------------------------------
class TestComplete(cmd.Cmd):
def __init__(self): cmd.Cmd.__init__(self)
def emptyline(self): pass
def do_start(self,s): print "start<%s>"%(s)
#-----------------------------------------------------------------------
def complete_start(self, text, line, begidx, endidx):
"""completions for start command"""
D('complete_start<%s,%s,%s,%s>'% \
(text,line,begidx,endidx))
# works when replacing '-' with '_'
choices='i_far i_09349 i_5sjdk i_foo far foo z_foo'.split()
choices='i-far i-09349 i-5sjdk i-foo far foo z-foo'.split()
matches=[]
for x in choices:
if x.startswith(text):
D('startswith<%s,%s>'%(text,x))
matches.append(x)
D('ret %s'%matches)
return matches
cc=TestComplete()
while True:
cc.cmdloop()
Cmd()使用readline模块,该模块默认使用以下定界符集:
>>> readline.get_completer_delims()
`~!@#$%^&*()-=+[{]}\|;:'",<>/?
您可以使用readline.set_completer_delims
选择一个定界符集,以排除不需要的字符。
import readline
class TestComplete(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
readline.set_completer_delims(' ') # space is the only delimiter now
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.