Search code examples
pythoncmdtab-completiontilde

Cmd module '~' completion


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.


Solution

  • Expanding on the answer from: https://stackoverflow.com/a/6657975/1263565

    You could override the cmd module's completedefault() method with:

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

    with the complete method looking like:

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

    This should now allow ~ expansion.