我在脚本中使用readline
来提供输入历史记录和基于历史记录的自动完成功能。
现在我希望它也完成bash命令。例如。建议$PATH
中的可执行文件,列出给定目录中的项目。
我必须手动实现吗?
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
with open(histfile) as f:
for line in f:
for item in line.strip().split():
commands.append(item)
def completer(text, state):
options = [i for i in commands if i.startswith(text)]
if state < len(options):
return options[state]
else:
return None
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
try:
readline.read_history_file(histfile)
# default history len is -1 (infinite), which may grow unruly
readline.set_history_length(1000)
except FileNotFoundError:
pass
atexit.register(readline.write_history_file, histfile)