How to code autocompletion in python?

前端 未结 6 1797
暖寄归人
暖寄归人 2020-11-27 11:20

I\'d like to code autocompletion in Linux terminal. The code should work as follows.

It has a list of strings (e.g. \"hello, \"hi\", \"how are you\", \"goodbye\", \"

6条回答
  •  醉话见心
    2020-11-27 11:33

    I guess you will need to get a key pressed by the user.

    You can achieve it (without pressing enter) with a method like this:

    import termios, os, sys
    
    def getkey():
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
        new[6][termios.VMIN] = 1
        new[6][termios.VTIME] = 0
        termios.tcsetattr(fd, termios.TCSANOW, new)
        c = None
        try:
            c = os.read(fd, 1)
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, old)
        return c
    

    Then, if this key is a tab key (for example, that's something you need to implement), then display all possibilities to user. If that's any other key, print it on stdout.

    Oh, of course you will need to have getkey() looped in a while, as long as the user hits enter. You can also get a method like raw_input, that will get the whole word sign by sign, or display all the possibilities, when you hit a tab.

    At least that's the item, you can start with. If you achieve any other problems, than write about them.

    EDIT 1:

    The get_word method can look like this:

    def get_word():
        s = ""
        while True:
            a = getkey()
            if a == "\n":
                break
            elif a == "\t":
                print "all possibilities"
            else:
                s += a
    
        return s
    
    word = get_word()
    print word
    

    The issue I'm occuring right now is the way to display a sign, you have just entered without any enteres and spaces, what both print a and print a, does.

提交回复
热议问题