【问题标题】:How to set a default editable string for raw_input?如何为 raw_input 设置默认的可编辑字符串?
【发布时间】:2011-07-21 03:53:32
【问题描述】:

我正在使用 Python 2.7 的 raw_input 从标准输入读取数据。

我想让用户更改给定的默认字符串。

代码:

i = raw_input("Please enter name:")

控制台:

Please enter name: Jack

应该向用户显示Jack,但可以将其更改(退格)为其他内容。

Please enter name: 参数将是raw_input 的提示,并且该部分不应由用户更改。

【问题讨论】:

标签: python input raw-input


【解决方案1】:

你可以这样做:

i = raw_input("Please enter name[Jack]:") or "Jack"

这样,如果用户只按回车键而不输入任何内容,“i”将被分配“Jack”。

【讨论】:

  • 这不符合问题。 Jack 不可编辑。
  • 但这是提供默认输入的常见 Unix 模式。如果您想接受默认值,只需按 Enter。
  • @chubbsondubs 问题不在于常见的 Unix 模式
【解决方案2】:

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://stackoverflow.com/a/2533142/445131

【讨论】:

  • 这应该也适用于 Windows 还是只适用于 Linux?
  • 你是天才!太棒了!
  • @ChaimG:不幸的是:pip install readline 产生 error: this module is not meant to work on Windows
【解决方案3】:

在 dheerosaur 的回答中,如果用户在现实中按 Enter 选择默认值,它不会被保存,因为 python 认为它是 '' 字符串,所以在什么 dheerosaur 上扩展一点。

default = "Jack"
user_input = raw_input("Please enter name: %s"%default + chr(8)*4)
if not user_input:
    user_input = default

Fyi .. 退格的ASCII value08

【讨论】:

  • 这是一个巧妙的技巧,谢谢。仍然不是我想要的,因为用户无法真正更改给定的默认字符串或使用箭头键进行导航。当然可以解决这个问题,但对于这样一个小功能来说,这有点超出了范围。
  • 不应该是'chr(8)*len(default)'吗?
  • Jack 只是打印,但没有设置为默认值。
【解决方案4】:

我只添加这个是因为您应该编写一个简单的函数以供重用。这是我写的:

def default_input( message, defaultVal ):
    if defaultVal:
        return raw_input( "%s [%s]:" % (message,defaultVal) ) or defaultVal
    else:
        return raw_input( "%s " % (message) )

【讨论】:

  • 这不符合问题。
  • 我重新阅读了这个问题,我仍然认为它确实如此。你可能想更好地解释你的立场。
  • @chubbsndubs 从问题中引用:“但可以将(退格)更改为其他内容”。这意味着用户应该能够编辑默认值。
  • 你太迂腐了。我的建议以稍微不同的方式为 OP 提供了他们要求的功能。这暗示如果 OP 可以改变他们的要求,我认为这是非常小的改变,那么这个解决方案将适用于他们。如果不好,答案是你不能用 raw_input() 来做,你可能正在寻找一个使用 readline 的非便携式解决方案。
【解决方案5】:

在有readline的平台上,可以使用这里描述的方法:https://stackoverflow.com/a/2533142/1090657

在 Windows 上,您可以使用 msvcrt 模块:

from msvcrt import getch, putch

def putstr(str):
    for c in str:
        putch(c)

def input(prompt, default=None):
    putstr(prompt)
    if default is None:
        data = []
    else:
        data = list(default)
        putstr(data)
    while True:
        c = getch()
        if c in '\r\n':
            break
        elif c == '\003': # Ctrl-C
            putstr('\r\n')
            raise KeyboardInterrupt
        elif c == '\b': # Backspace
            if data:
                putstr('\b \b') # Backspace and wipe the character cell
                data.pop()
        elif c in '\0\xe0': # Special keys
            getch()
        else:
            putch(c)
            data.append(c)
    putstr('\r\n')
    return ''.join(data)

注意方向键在windows版本下不起作用,使用时什么都不会发生。

【讨论】:

    【解决方案6】:

    对于具有gitbash/msys2cygwinwindows 用户,您可以通过python 子进程在readline 中使用它。这是一种 hack,但效果很好,不需要任何第三方代码。对于个人工具,这非常有效。

    特定于 Msys2:如果您希望 ctrl+c 立即退出,您需要使用
    winpty python program.py

    运行您的程序
    import subprocess
    import shlex
    
    def inputMsysOrCygwin(prompt = "", prefilled = ""):
        """Run your program with winpty python program.py if you want ctrl+c to behave properly while in subprocess"""
        try:
            bashCmd = "read -e -p {} -i {} bash_input; printf '%s' \"$bash_input\"".format(shlex.quote(prompt), shlex.quote(prefilled))
            userInput = subprocess.check_output(["sh", "-c", bashCmd], encoding='utf-8')
            return userInput
        except FileNotFoundError:
            raise FileNotFoundError("Invalid environment: inputMsysOrCygwin can only be run from bash where 'read' is available.")
    
    userInput = ""
    try:
        #cygwin or msys2 shell
        userInput = inputMsysOrCygwin("Prompt: ", "This is default text")
    except FileNotFoundError:
        #cmd or powershell context where bash and read are not available 
        userInput = input("Prompt [This is default text]: ") or "This is default text"
    
    print("userInput={}".format(userInput))
    

    【讨论】:

      【解决方案7】:

      试试这个:raw_input("Please enter name: Jack" + chr(8)*4)

      backspace 的 ASCII 值是08

      【讨论】:

      • Jack 只是打印,但未设置为默认值。
      • @buhtz 感谢您的指出。请随时编辑答案。
      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 2012-05-02
      • 2011-04-09
      • 2015-03-23
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多