我正在使用 Python 2.7raw_input
从标准输入读取数据。
我想让用户更改给定的默认字符串。
代码:
i = raw_input("Please enter name:")
安慰:
Please enter name: Jack
应该向用户呈现,Jack
但可以将其更改(退格)为其他内容。
参数将Please enter name:
是提示,raw_input
并且该部分不应由用户更改。
你可以这样做:
i = raw_input("Please enter name[Jack]:") or "Jack"
这样,如果用户只按返回而不输入任何内容,“i”将被分配为“Jack”。
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)
有关此处发生的事情的更多信息:
在 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 value
退格键是08
我只添加这个是因为您应该编写一个简单的函数以供重用。这是我写的:
def default_input( message, defaultVal ):
if defaultVal:
return raw_input( "%s [%s]:" % (message,defaultVal) ) or defaultVal
else:
return raw_input( "%s " % (message) )
在带有 的平台上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 版本,使用时不会发生任何事情。
对于Windows用户,gitbash/msys2
或者cygwin
您可以通过 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))
尝试这个:raw_input("Please enter name: Jack" + chr(8)*4)
backspace
的ASCII 值为08
。