【发布时间】:2011-04-29 10:31:59
【问题描述】:
我有一个 Cmd 控制台设置为自动完成 Magic: the Gathering 收藏管理系统的卡片名称。
它使用文本参数查询数据库中的卡片,并使用结果自动完成/建议卡片。
但是,这些卡片名称有多个单词,并且 Cmd 会从 last 空格到行尾运行自动补全。
例如:
mtgdb> add Mage<tab><tab>
Mage Slayer (Alara Reborn) Magefire Wings (Alara Reborn)
mtgdb> add Mage S<tab><tab>
Sages of the Anima (Alara Reborn)
Sanctum Plowbeast (Alara Reborn)
Sangrite Backlash (Alara Reborn)
Sanity Gnawers (Alara Reborn)
Sen Triplets (Alara Reborn)
[...]
mtgdb> add Mage Sl<tab>
mtgdb> add Mage Slave of Bolas (Alara Reborn)
我尝试从line 参数中手动获取我想要的内容,它从数据库中获取了我想要的结果,但这未能覆盖第一个单词:
mtgdb> add Mage Sl<tab>
mtgdb> add Mage Mage Slayer (Alara Reborn)
最后,我需要自动完成器像这样工作:
mtgdb> add Mage Sl<tab>
mtgdb> add Mage Slayer (Alara Reborn)
除了上面的手动解析尝试之外,我还尝试用加号替换空格,并发现 Cmd 也非常乐意拆分这些空格。用下划线替换空格是可行的,但是 Unhinged 中有一张名为 _____ 的卡片,所以我必须通过杂技来破解字符串,因为我不能只是 line.replace("_", " ")。
这是一些可运行的测试代码:
import cmd
commands = [
"foo",
"foo bar blah",
"bar",
"bar baz blah",
"baz",
"baz foo blah"]
class Console(cmd.Cmd):
intro = "Test console for" + \
"http://stackoverflow.com/questions/4001708/\n" + \
"Type \"cmd<space><tab><tab>\" to test " + \
"auto-completion with spaces in commands\nwith " + \
"similar beginings."
def do_cmd(self, line):
print(line)
def complete_cmd(self, text, line, start_index, end_index):
if text:
return [command for command in commands
if command.startswith(text)]
else:
return commands
if __name__ == "__main__":
command = Console()
command.cmdloop()
【问题讨论】:
-
这里有一些很好的信息:stackoverflow.com/questions/187621/…
-
能否提供可运行的测试代码?这似乎可以解决
-
是的,我也看到了那个,@offsound,这是我想到使用 Cmd 的地方。我会编写一些测试代码。
标签: python command-line autocomplete