input() :: 使用退格键和箭头键
我有一个Python脚本,它通过内置的input()函数从用户那里获取信息。
我想问的是,为什么退格键和方向键不能正常工作?我该怎么做才能让它们按预期功能正常使用呢?
我遇到问题的一个简单例子是……
#!/usr/bin/env python3
while 1:
x=input("enter integer: ")
y=int(x)*17
print(y)
这里有一个使用它的例子。
./tester
enter integer: 3
51
enter integer: 17
289
enter integer: 172^[[D^[[D^H
Traceback (most recent call last):
File "./tester", line 4, in <module>
y=int(x)*17
ValueError: invalid literal for int() with base 10: '172\x08'
在尝试用方向键和退格键删除'1'时,出现了^[[D^[[D^H,而不是正常地向左移动两个空格并删除'1',这导致程序崩溃。
我该怎么做才能让所有的键都正常工作呢?
3 个回答
1
为了补充@t-8ch的回答,这里有一个示例:
import sys
print("Enter choice(1-4):")
res = sys.stdin.readline() # used in place of input()
# to strip the new line from stdin like '4\n' and then convert str to int
ch = int(res.strip())
1
27
从标准库中导入 readline
模块。这个模块会自动处理标准输入。
比如说:
import readline
while True:
response = input("> ").strip()
if response.lower() == "quit":
break
print(f"You entered '{response}'")