将Tab绑定到Python 3.8中的readline.completion时出现奇怪的结果

问题描述

我正在运行带有Python 3.8.2的Ubuntu 20.4,并在Python中的readline界面上遇到了奇怪的行为。

我的目标是提供一种输入功能,该功能允许在终端上的给定位置从给定字符串的列表中进行选择,或者-仅输入所需的字符串。我的代码几乎可以运行,直到由于某些原因导致某些字符串损坏为止。

我的代码如下


    import readline
    class __readlineCompleter(object):
        """
        Cycles through a list of potential strings the user might want to enter
        """
    
        def __init__(self,options):
            self.options = list(options)  #sorted([item for item in options])
            self.index = 0
    
            return
    
        def complete(self,text,state):
            if state == 0:
                if text and not text in self.options:
                    self.options.append(text)
    
                self.index += 1
                if self.index >= len(self.options):
                    self.index = 0
    
                return self.options[self.index]
            else:
                return None
    
    def input_at(x_pos,y_pos,_text,_prefill,_choices):
        """
        positions the cursor at x_pos,prints text if given and reads a string from stdin
        @param x_pos(int):          row to print at
        @param y_pos(int):          columns to print at
        @param _text(string):       text to print before the input field
        @param _prefill(string):    text as default input
        @param _choices(list):      list of strings as proposed input values
        @return: (string):          input given by user,or False
        """
    
        _myPrompt = "\033[{};{}H{}\033[0m".format(x_pos,_text)
    
        if type(_choices) in (set,list) and len(_choices):
            _choices = set([x for x in _choices])
            readline.set_completer(__readlineCompleter(_choices).complete)
            readline.set_completer_delims('')
            readline.parse_and_bind('tab: menu-complete')
    
        try:
            _input = input(_myPrompt)
        except KeyboardInterrupt as EOFError:
            _input = False
    
        return _input

就像我说的那样,这很好用,一旦按下 TAB 用户就会看到与 _choices 不同的选项,按下 Enter 会返回所选条目。或者,用户可以手动输入字符串。所以这就是我的意图,直到涉及到某些字符串为止。所以当我这样调用上面的代码


    _temp = [ 'Julius Papp','J‐Live','Mr. Electric Triangle','MullerAnustus Maximilian']
    _result = input_at(15,"Name:   ",_temp[0],_temp)

cli看起来像这样(在我按 Tab 的每一行之后,下一行显示输出

Name:   
Name:    Julius Papp  
Name:    J-Live  
Name:    Mr. Electric Triangle  
Name:    MullerAnustus Maximilian  
Name:    MullerAnustJulius Papp
                    ***********      

(我在后面的输出中插入了星星,以显示错误显示) 因此,最终尝试以某种方式破坏了 linebuffer ;任何后续的 Tab 均可按预期工作。尽管如此,生成 _input _choices 的有效成员,因此这似乎只是一个显示问题。

有人知道为什么字符串MullerAnustus Maximilian表现得如此奇怪吗?

解决方法

我自己使用enter image description here库解决了这个问题。