我有一个python脚本(用作命令行界面),等待使用该input
函数进行输入查询。
while True:
query = input('Enter query: ')
thread = Thread(target=exec_query, args=(query,))
thread.start()
同时,辅助线程正在执行此类查询。使用该print
功能,查询的输出被打印到命令行。
def exec_query(query_data):
# doing a complex data processing ...
print('results of the query')
因此,将打印功能的输出写在'Enter query: '
主线程中第二次执行打印功能所打印的前缀之后:
Enter query: {the query}
Enter query: results of the query
我想实现将print函数的输出插入到前缀之前'Enter query: '
(或者看起来是这种情况):
Enter query: {the query}
results of the query
Enter query:
我已经通过几种方法,但是没有找到一个好的解决方案。一种解决方法是通过添加前缀来删除前缀,'\x1b[1A\x1b[2K'
并在打印查询执行的输出后写回前缀。这里的问题是,我不知道如何重建此时用户可能已经插入的不完整的用户输入(查询)。
使用此从终端读取1个字符
str
通过bytes.decode()
msvcrt.getch
使用.getche
_GetchWindows.__call__
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)
提示将不能被退格键擦除,并且记住字符串
大更新
我使用curses
模块而不是msvcrt
(最初建议)
这实际上存在与您类似的问题(简化了很多模拟),
但是解决了问题的核心
只要不超过3个字符,就需要输入。
如果写的> = 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以轻松管理更多的事情,例如用箭头移动,但这不在此问题的范围内
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句