使用这个Read 1 char from terminal
- 返回字节
- 不回显(打字不可见)
- 在
_GetchWindows.__call__ 中使用.getche 而不是msvcrt.getch
-
msvcrt 未全局导入
做类似的事情
while input != '\r': # or some other return char, depends
input += getch().decode()
和
# in front of erase
while msvcrt.kbhit(): # read while there is something to read
remember_input += getch().decode()
print(erase)
# and than you should return remember_input to stdin somehow (try msvcrt.putch)
由于复杂性(使用线程编写(我是新手)、输入/输出控制(因为我的 vsc 终端每次都讨厌我),我自己没有做过),可能还有更多原因太累了想不起来),
但我相信你不会退出
编辑:哦,是的
我忘了提到你可能还想写你自己的print和input,
在这种情况下有用的东西是input(prompt, remember_string)
提示将无法被退格键删除,并且 remember_string 会
重大更新
我使用curses 模块而不是msvcrt(如最初建议的那样)
这实际上存在与您类似的问题(非常简化的模拟),
但解决了问题的核心
- 接收输入
- 发生某事时删除行并在该行中写入消息
- 在那里重新输入已经写好的东西
这需要输入,只要它是
如果写入 >= 4 个字符,它将执行 (3.) 对您来说完成查询的内容,
然后用旧输入再次请求输入。
当按下 ENTER 时,完成输入
import curses
import curses.ascii as ascii
def getch(stdscr: curses.window):
'return single char'
a = stdscr.get_wch()
stdscr.refresh()
return a
def prompt(stdscr: curses.window):
'write prompt for input'
addstr(stdscr, "Enter query: ")
def addstr(stdscr: curses.window, str):
'write string to window'
stdscr.addstr(str)
stdscr.refresh()
def del_line(stdscr: curses.window):
'deletes line in which cursor is'
row, col = stdscr.getyx()
stdscr.move(row, 0)
stdscr.clrtoeol()
@curses.wrapper
def main(stdscr: curses.window):
# next 3 lines were on some tutorial so I left them be
# Clear screen
stdscr.clear()
curses.echo()
# I will use marks like #x.y to indicate places
q = ''
while True: #EDIT from `for (5)` to `while`
prompt(stdscr)
addstr(stdscr, q) # at the beginning & after enter is pressed, q==''
# else it is old input (that was >= 4 chars
for i in range(4): # range 4 to take 4 or less chars
a = getch(stdscr) #read charby char
if ascii.isalnum(a): #letters & numbers
q += a
elif a == '\n' or a == '\r': # enter pressed == input finished
stdscr.addstr(f"\nfinished input {q}\n")
q = ''
break
else: # this block happens (in py) if no break occurred in loop
# that means, in this case, that ENTER was not pressed, i.e. input is stillongoing
# but since it is > 4 chars it is briefly interrupted to write message
del_line(stdscr)
addstr(stdscr, "Input interupted\n")
return
测试
运行这个程序(我建议直接双击文件打开std终端,因为其他终端可能有针对这个[程序]的东西)
(E 代表 ENTER)
并输入:abcE、abcdefE、abcdefghijE
看看这是做什么的
附言
这可能会解决您的问题,但此模块的功能更大,
而且我不想写太多复杂的 API。
解决方案是编写 API 来轻松管理更多的事情,比如用箭头移动,但这不在这个问题的范围内