Is it possible to prefill a input() in Python 3's Command Line Interface?

99封情书 提交于 2019-11-29 15:59:43

问题


I'm using Python 3.2 on Ubuntu 11.10 (Linux). A piece of my new code looks like this:

text = input("TEXT=")

Is it possible to get some predefined string after the prompt, so I can adjust it if needed? It should be like this:

python3 file
TEXT=thepredefinedtextishere

Now I press Backspace 3 times

TEXT=thepredefinedtextish

Now I press Enter, and the variable text should be thepredefinedtextish


回答1:


If your Python interpreter is linked against GNU readline, input() will use it. In this case, the following should work:

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


来源:https://stackoverflow.com/questions/8505163/is-it-possible-to-prefill-a-input-in-python-3s-command-line-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!