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



我正在运行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 = "33[{};{}H{}33[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看起来是这样的(在我按下选项卡的每一行之后,下一行显示输出(

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

(我在后一个输出中插入了星号,以显示"错误"显示(因此,不知何故,最后一次尝试破坏了行缓冲区;任何后续的选项卡都能按预期工作。然而,生成的_input_choices的有效成员,因此这似乎只是一个显示问题。

有人知道为什么字符串MullerAnustus Maximilian的行为如此奇怪吗?

我自己通过使用rl 2.4–GNU Readline Bindings库解决了这个问题。

最新更新