我知道我可以这样做,以确保python中的选项卡完成效果.
import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
'email', 'foobar', 'foo']
def complete(text, state):
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')
Run Code Online (Sandbox Code Playgroud)
我现在对使用目录完成制表符感兴趣.(/ home/user/doc>标签)
我怎么去做这样的任务?
我正在使用Python的Cmd.cmd创建一个命令行工具,我想添加一个带有filename参数的"load"命令,它支持tab-completion.
import os, cmd, sys, yaml
import os.path as op
import glob as gb
def _complete_path(path):
if op.isdir(path):
return gb.glob(op.join(path, '*'))
else:
return gb.glob(path+'*')
class CmdHandler(cmd.Cmd):
def do_load(self, filename):
try:
with open(filename, 'r') as f:
self.cfg = yaml.load(f)
except:
print 'fail to load the file "{:}"'.format(filename)
def complete_load(self, text, line, start_idx, end_idx):
return _complete_path(text)
Run Code Online (Sandbox Code Playgroud)
这适用于cwd,但是,当我想进入subdir时,在subdir /之后,complete_load函数的"text"变为空白,所以_complete_path func再次返回cwd.
我不知道如何使用tab-completion获取subdir的内容.请帮忙!