Python 将光标向前移动两位

Python move cursor two places forward

我编写了下面的程序,旨在充当我即将为大学项目构建的聊天终端 UI。在目前的状态下,目标是始终让最后一行作为写入消息的区域,当按下回车键时,消息写在上面,最后一行再次变为空白。

如果这就是我想要的,那很好用。但是,我也想在最后一行的开头总是有一些 "prompt symbols",即这里的 :>。为了做到这一点,当按下回车键时,整个当前行被删除,打印出裸消息,插入一个换行符,最后我希望在新行中打印 :> 并重复。

然而,实际情况是提示字符串确实被打印出来了,但是光标在按下第一个回车键后,从行首开始,这意味着任何后续输入都会覆盖提示字符。由于某种原因,这不是第一次发生,在其他任何事情发生之前打印第一个提示。

所以最后,我想要一种方法,当打印换行符时,光标实际上在两个提示字符之后开始。关于终端的功能,这就是我想要的,因此我想找到一种简单的方法来解决这个问题并完成它,而不是干预 ncurses 库等。谢谢大家的宝贵时间。代码中的兴趣点是在最后一个 while 循环中发生我想发生的任何事情。

代码应为 运行 和 Python3。

import sys
from string import printable
import termios
import tty

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
    screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()
class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            # ch = sys.stdin.read(1)
            ch = sys.stdin.read(1)[0]
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

# enter: ord 13
#backspace: ord 127

current_input = ""
prompt_msg = ":> "

print(10*"\n"+prompt_msg,end="")

getch = _Getch()

def clear_input():
    linelen = (len(current_input)+len(prompt_msg))
    sys.stdout.write("\b"*linelen+" "*linelen+"\b"*linelen)
    sys.stdout.flush()


while(True):

    ch=getch()
    if ord(ch)==3:# ctrl+c
        exit()
    # >>>>>>>.POINT OF INTEREST<<<<<<<<<<<
    if ord(ch)==13:# enter
        clear_input()
        print(current_input)
        current_input = ""

        # print(prompt_msg,end="")
        sys.stdout.write(prompt_msg)
        sys.stdout.flush()

    if ord(ch)==127 and len(current_input)>0:# backspace
        sys.stdout.write("\b"+" "+"\b")
        sys.stdout.flush()
        current_input=current_input[:-1]
    if ch in printable or ord(ch)>127: # printable
        current_input+=ch
        sys.stdout.write(ch)
        sys.stdout.flush()

我没有试图让指针向前移动两个位置——我没有找到答案——我只是简单地从 [=10 中删除了回车 return 字符(“\r”) =] string 在每个应该完成的地方 - 字符串中似乎存在流氓运输 return 字符,这导致了问题。