2

I have been playing around with the cmd python module and was looking at the text completion function. I have been trying to get it to expand/recognise '~' to my home directory but with no avail.

I've noticed that I can handle default completion by overriding the completedefault(self, *ignored) method from the cmd module. Where ignored is a tuple of the text, line, begidx, endidx. If I type in the command my_command ./folder the text parameter will be './folder' and this mean I can do something like: glob.glob(text + '*') which returns a list of all the files in that folder. However, if I now do my_command ~/folder the text variable now only contains /folder, so I am unable to use os.path.expanduser(text) to determine the absolute path of that folder and show all the files in that folder.

Basically I am wondering if someone could point me in the right direction in order to expand paths with a ~ in it.

4

1 回答 1

2

扩展来自: https ://stackoverflow.com/a/6657975/1263565的答案

您可以使用以下命令覆盖 cmd 模块的completedefault()方法:

def completedefault(self, *ignored):
        # Set the autocomplete preferences
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(complete)

完整的方法如下所示:

def complete(text, state):
    return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]

这现在应该允许~扩展。

于 2014-02-12T10:58:50.413 回答