是否可以在 Python 3 的命令行界面中预填充 input()? [英] Is it possible to prefill a input() in Python 3's Command Line Interface?

查看:30
本文介绍了是否可以在 Python 3 的命令行界面中预填充 input()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ubuntu 11.10 (Linux) 上使用 Python 3.2.我的一段新代码如下所示:

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

现在我按 Backspace 3 次

TEXT=thepredefinedtextish

现在我按Enter,变量text应该是thepredefinedtextish

推荐答案

如果您的 Python 解释器链接到 GNU readline,input() 将使用它.在这种情况下,应执行以下操作:

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

这篇关于是否可以在 Python 3 的命令行界面中预填充 input()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆