Change how Python Cmd Module handles autocompletion

后端 未结 3 1989
旧时难觅i
旧时难觅i 2021-02-04 10:40

I have a Cmd console set up to auto-complete card names for a Magic: the Gathering collection management system.

It uses the text parameter to query the database for car

相关标签:
3条回答
  • 2021-02-04 10:49

    It shouldn't need to be overly complicated. Something like the following:

    import cmd
    
    completions = [
        'Mage Slayer (Alara Reborn)',
        'Magefire Wings (Alara Reborn)',
        'Sages of the Anima (Alara Reborn)',
        'Sanctum Plowbeast (Alara Reborn)',
        'Sangrite Backlash (Alara Reborn)',
        'Sanity Gnawers (Alara Reborn)',
        'Sen Triplets (Alara Reborn)'
    ]
    
    class mycmd(cmd.Cmd):
        def __init__(self):
            cmd.Cmd.__init__(self)
    
        def do_quit(self, s):
            return True
    
        def do_add(self, s):
            pass
    
        def complete_add(self, text, line, begidx, endidx):
            mline = line.partition(' ')[2]
            offs = len(mline) - len(text)
            return [s[offs:] for s in completions if s.startswith(mline)]
    
    if __name__ == '__main__':
        mycmd().cmdloop()
    
    0 讨论(0)
  • 2021-02-04 11:00

    You could do readline.set_completer_delims('').

    However, your complete_* functions won't be called anymore; you will have to override Cmd.complete or Cmd.completenames. Look at the sourcecode of the cmd module for details.

    0 讨论(0)
  • 2021-02-04 11:11

    I did override of the cmdloop function, and it was pretty straightforward. I didn't have to change anything else. Just copy the cmdloop function from the module (find code by doing import cmd, cmd.__file__), and add the two lines for changing delimiters:

        try:
           import readline
           self.old_completer = readline.get_completer()
           readline.set_completer(self.complete)
           readline.parse_and_bind(self.completekey+": complete")
           # do not use - as delimiter
           old_delims = readline.get_completer_delims() # <-
           readline.set_completer_delims(old_delims.replace('-', '')) # <-
        except ImportError:
            pass
    

    That did it for me. In your case you may want to remove whichever delimiter is causing the issues.

    0 讨论(0)
提交回复
热议问题