使用Python2.7获取raw_input并设置默认值:
将以下内容保存到名为a.py的文件中:
import readline
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return raw_input(prompt)
finally:
readline.set_startup_hook()
default_value = "an insecticide"
stuff = rlinput("Caffeine is: ", default_value)
print("final answer: " + stuff)
运行程序后,它会停止并向用户呈现以下内容:
el@defiant ~ $ python2.7 a.py
Caffeine is: an insecticide
光标在末尾,用户按退格键直到“杀虫剂”消失,然后输入其他内容,然后按回车键:
el@defiant ~ $ python2.7 a.py
Caffeine is: water soluable
程序以以下方式结束,最终答案取决于用户输入的内容:
el@defiant ~ $ python2.7 a.py
Caffeine is: water soluable
final answer: water soluable
等同于上面,但适用于Python3:
import readline
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt)
finally:
readline.set_startup_hook()
default_value = "an insecticide"
stuff = rlinput("Caffeine is: ", default_value)
print("final answer: " + stuff)
这里有更多关于发生了什么的信息:
https://dev59.com/NHE85IYBdhLWcg3w8IbK#2533142