簡體   English   中英

在 Python 3.8 中將 Tab 綁定到 readline.completion 時出現奇怪的結果

[英]Strange result when binding Tab to readline.completion in Python 3.8

我正在運行 Ubuntu 20.4 w/ Python 3.8.2 並在 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, y_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, y_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, 0, "Name:   ", _temp[0], _temp)

cli 看起來像這樣(在我按下Tab的每一行之后,下一行顯示輸出)

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

(我在后面的 output 中插入了星星來顯示“錯誤”的顯示)所以最后的嘗試以某種方式破壞了linebuffer 任何后續選項卡都按預期工作。 盡管如此,生成的_input_choices的有效成員,所以這似乎只是一個顯示問題。

有誰知道為什么字符串MullerAnustus Maximilian表現得如此奇怪?

我自己解決了這個問題,方法是使用rl 2.4 – GNU Readline Bindings庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM