Python readline tab completion with '$'

I'm creating a custom interactive console using Cmd.py and am using readline for tab completion. This is being tested on a Mac, using python 2.7.1.

I define my completion candidates using complete_[cmd_name] so that cmd.py can use it to get a list of possible completions. The argument that is being completed is a string. My candidate completions is a list of strings. Everything works in normal cases. The problem is when the argument starts with a '$'. Readline is apparently stripping off the leading '$' character and it is messing up my compare when I construct the candidate list.

For example:

completion_list = ['test', 'another_test', '$t_problem_case']

Input: cmd te[tab] This correctly completes the word 'test'.

Input: cmd $t_[tab] No completion is made

Input: cmd $te[tab] Incorrectly completes to $test

Ok, so the problem at first seems obvious. I think readline is using '$' as a delimiter. This is easily fixed by using:

readline.set_completer_delims(readline.get_completer_delims().replace("$", ""))

Only this does not work. The same thing still happens.

The completion function takes in the parameters 'text' and 'line', where text is the argument being completed (the one missing the '$') and line is the complete line. Trying to outsmart readline I check to see if the argument actually has a $ in the line, and if it does I append this to the argument I'm checking so that I can correctly filter the candidates. This almost works.

Input: $t[tab] Correctly completes the string... almost. Because readline is ignoring my '$' it doesn't bother to remove this character on the replace. The result is actually "$$t_problem_case".

As a final effort I modified the cmd.py default complete function to return the match with the '$' taken off the front. This way readline would actually be replacing with 't_problem_case' and everything would look correct. This is a step in the right direction, but the problem is the tab-completion suggestions now don't show the '$'. So in the suggestions '$t_problem_case' would show up as 't_problem_case'.

Is there a correct way to fix this problem?

链接地址: http://www.djcxy.com/p/56418.html

上一篇: 在使用.readlines()时摆脱\ n

下一篇: 使用'$'的Python readline选项卡完成