如何更改Python中input()函数中用户输入的光标位置



在使用input()函数时,我希望从用户获取或接收一个字符串到一个变量。那么,可以在方括号内输入而不是纯文本吗?例如

a = input("-->")

这显示了这样的输出:

-->

但是我可以得到这样的输出吗:

--> [ _ ]

并在方括号内输入。(_表示光标。(

调用input()时操作光标位置需要使用ANSI转义序列进行破解。(请参阅@chepner的答案。(为了更正确地完成您想要的操作,您需要使用一个可以操作终端的库,例如curses。

你可以。如果您的终端支持ANSI转义序列,则可以通过输出33[s来保存当前光标位置,并使用33[u将光标移回上次保存的位置。然后您对input的呼叫将看起来像

a = input("--> [33[s ]33[u")

然而,这纯粹是视觉上的:没有什么能阻止你在方括号之外键入"beyond"。主要限制是input本身对终端一无所知;它只是从行缓冲的标准输入中读取。input在输入完整的行之前不返回任何内容;在此之前,它只是等待终端发送一些。像curses这样的库提供了更精确的处理;例如,如果您试图在提示中键入超过]的内容,它可能会停止对按键的响应。

下面的代码片段使用curses,将处理标准可见的ascii字符、删除字符和换行符(用于提交(。

from curses import wrapper
def prompt(stdscr, prompt_template="--> [ {} ]"):
user_inp = ""
display_str = prompt_template.format(user_inp)
stdscr.addstr(0, 0, display_str)
while True:
inp_ch = stdscr.getch()
# standard ASCII characters
if 32 <= inp_ch <= 126:
user_inp += chr(inp_ch)
elif inp_ch in (8, 127, 263): # BS, DEL, Key_Backspace
user_inp = user_inp[:-1]
elif inp_ch == 10: # is newline, enter pressed
break
else: # all other characters are ignored
continue
display_str = prompt_template.format(user_inp)
stdscr.erase()
stdscr.addstr(0, 0, display_str)
stdscr.refresh()
return user_inp
print(wrapper(prompt))

最新更新