在Python 3的命令行界面中可以预填充input()吗?
我在Ubuntu 11.10上使用Python 3.2。我的新代码的一部分看起来是这样的:
text = input("TEXT=")
我想知道能不能在提示符后面显示一个预设的字符串,这样我就可以根据需要进行调整。它应该像这样:
python3 file
TEXT=thepredefinedtextishere
现在我按了 Backspace 三次
TEXT=thepredefinedtextish
然后我按 Enter,这个时候变量 text
应该是 thepredefinedtextish
2 个回答
0
我觉得你想要的是一种更流畅的效果,但有个简单的方法可以做到:
inputstring = input("Input your text here ('test' if ignored): ")
if inputstring == '' : inputstring = 'test'
38
如果你的Python解释器是和GNU readline库连接在一起的,那么input()
这个函数就会使用这个库。在这种情况下,下面的代码应该可以正常运行:
import readline
def input_with_prefill(prompt, text):
def hook():
readline.insert_text(text)
readline.redisplay()
readline.set_pre_input_hook(hook)
result = input(prompt)
readline.set_pre_input_hook()
return result