【问题标题】:Python move cursor two places forwardPython将光标向前移动两位
【发布时间】:2018-01-18 02:11:27
【问题描述】:

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

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

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

所以最后,我想要一种方法,让光标在打印换行符时在两个提示字符之后实际开始。这就是我想要的关于终端功能的全部内容,因此我想找到一种简单的方法来解决这个问题并完成它,而不是干预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()

【问题讨论】:

    标签: python python-3.x terminal text-cursor


    【解决方案1】:

    而不是试图让指针向前移动两个位置 - 我没有找到答案 - 我只是从 current_input 字符串中删除了每个应该的位置的回车符(“\r”)完成 - 字符串中似乎存在流氓回车字符,这导致了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      相关资源
      最近更新 更多