如何为 raw_input 设置默认的可编辑字符串?

发布于 2024-10-25 19:44:43 字数 382 浏览 1 评论 0原文

我使用 Python 2.7 的 raw_input 从标准输入读取。

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

代码:

i = raw_input("Please enter name:")

控制台:

Please enter name: Jack

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

请输入名称: 参数将是 raw_input 的提示,并且该部分不应由用户更改。

I'm using Python 2.7's raw_input to read from stdin.

I want to let the user change a given default string.

Code:

i = raw_input("Please enter name:")

Console:

Please enter name: Jack

The user should be presented with Jack but can change (backspace) it to something else.

The Please enter name: argument would be the prompt for raw_input and that part shouldn't be changeable by the user.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

时光与爱终年不遇 2024-11-01 19:44:45

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

光标位于末尾,用户按下退格键,直到“杀虫剂”消失,输入其他内容,然后按 Enter:

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

Python2.7 get raw_input and set a default value:

Put this in a file called 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)

Run the program, it stops and presents the user with this:

el@defiant ~ $ python2.7 a.py
Caffeine is: an insecticide

The cursor is at the end, user presses backspace until 'an insecticide' is gone, types something else, then presses enter:

el@defiant ~ $ python2.7 a.py
Caffeine is: water soluable

Program finishes like this, final answer gets what the user typed:

el@defiant ~ $ python2.7 a.py 
Caffeine is: water soluable
final answer: water soluable

Equivalent to above, but works in 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)

More info on what's going on here:

https://stackoverflow.com/a/2533142/445131

究竟谁懂我的在乎 2024-11-01 19:44:45

在 dheerosaur 的回答中,如果用户按 Enter 键选择现实中的默认值,它不会被保存,因为 python 认为它是 '' 字符串,所以对 dheerosaur.txt 进行了一些扩展。

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

仅供参考.. 退格键的 ASCII 值08

In dheerosaur's answer If user press Enter to select default value in reality it wont be saved as python considers it as '' string so Extending a bit on what dheerosaur.

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

Fyi .. The ASCII value of backspace is 08

趁微风不噪 2024-11-01 19:44:45

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

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

I only add this because you should write a simple function for reuse. Here is the one I wrote:

def default_input( message, defaultVal ):
    if defaultVal:
        return raw_input( "%s [%s]:" % (message,defaultVal) ) or defaultVal
    else:
        return raw_input( "%s " % (message) )
那支青花 2024-11-01 19:44:45

在具有 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 版本,使用时不会发生任何情况。

On platforms with readline, you can use the method described here: https://stackoverflow.com/a/2533142/1090657

On Windows, you can use the msvcrt module:

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)

Note that arrows keys don't work for the windows version, when it's used, nothing will happen.

乖不如嘢 2024-11-01 19:44:45

对于使用 gitbash/msys2cygwinwindows 用户,您可以通过 python 子进程使用它内置的 readline。这是一种黑客攻击,但效果很好,并且不需要任何第三方代码。对于个人工具来说,这非常有效。

Msys2 特定:如果您希望 ctrl+c 立即退出,则需要使用
运行您的程序
winpty python 程序.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))

For windows users with gitbash/msys2 or cygwin you can use it's built in readline through python subprocess. It is a sort of hack but works quite well and doesn't require any third party code. For personal tools this works really well.

Msys2 specific: If you want ctrl+c to immediately exit, you will need to run your program with
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))
維他命╮ 2024-11-01 19:44:45

试试这个: raw_input("请输入姓名:Jack" + chr(8)*4)

backspace 的 ASCII 值为 08

Try this: raw_input("Please enter name: Jack" + chr(8)*4)

The ASCII value of backspace is 08.

捂风挽笑 2024-11-01 19:44:44

你可以这样做:

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

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

You could do:

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

This way, if user just presses return without entering anything, "i" will be assigned "Jack".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文