如果使用sys.stdout.write
orprint
代替编写提示,则会发生这种情况raw_input
。以下脚本演示了它:
$ cat overwrite.py
import readline, sys
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
def set_completer(choices):
choices = sorted(map(str,choices))
def completer(txt, state):
if state == 0:
completer.options = [c for c in choices if c.startswith(txt)]
if state < len(completer.options):
return completer.options[state]
return None
readline.set_completer(completer)
set_completer(['foo','flup'])
sys.stdout.write('input: ')
x = raw_input()
print x
如果你运行python overwrite.py
,你会得到预期的提示:“input:”。如果您按一次退格键,则不会删除任何内容(我猜 readline 认为它已经在行首)。但是,如果您按“f”然后退格,则包括提示在内的整行都会被擦除。
必须遍历并替换我写到 stdout 的所有地方并且期望通过调用 raw_input 从用户那里获得输入是非常不方便的,所以我希望没有必要使用raw_input
. python 文档在 readline 方面一反常态地稀疏。