[英]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.