保持标准线在终端屏幕的顶部或底部

2024-09-28 20:52:25 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在写一个项目,在这个项目中我运行一个程序,不断地接收/发送消息到其他运行相同程序的计算机。在

数据的接收方/发送方正在线程上运行并打印到stdout。 我得到这样的东西:

[INFO] User 'blah' wants to send message to you.
[INFO] some other info
[MSG REC] Message 'hello' received from blah.

现在的问题是,有时我希望在终端中输入命令,问题是当我试图输入一个命令时,一条新的信息消息或MSG REC被打印到stdout。我有诸如quitstatus等命令

>>表示输入行。在

可能会发生这样的事情:

^{pr2}$

{但是{3}命令看起来很差,然后输入命令。每隔2-4秒会出现一条消息,因此这是一个问题。有没有解决这个问题的好办法?我尝试使用ansicursor命令在最后一行之前插入一个新行,这样最后一行将始终保持为输入行,我可以键入“stat”,稍等片刻,然后用“us”完成它,没有任何问题。在

我还看到有人推荐curses,但是试图将其与我的程序集成,会把我的输出格式和其他东西完全弄乱(我认为这可能是过火了)。在

那么,有没有一种简单的方法可以让线程在最后一行上方插入新的MSG REC行,这样最后一行将始终保持为输入行,>>;以及我键入的其他内容。在

在Linux上使用Python2.7。在

编辑:让詹姆斯·米尔斯的回答奏效的改变: 每当我的线印一条新的线时,我都要用这个。在

myY, myX = stdscr.getyx();        
str = "blah blah"; #my message I want to print
stdscr.addstr(len(lines), 0, str)
lines.append(str)
stdscr.move(myY, myX) #move cursor back to proper position

Tags: to项目命令程序info消息message键入
1条回答
网友
1楼 · 发布于 2024-09-28 20:52:25

下面是一个基本示例:

代码:

#!/usr/bin/env python

from string import printable
from curses import erasechar, wrapper

PRINTABLE = map(ord, printable)

def input(stdscr):
    ERASE = input.ERASE = getattr(input, "ERASE", ord(erasechar()))
    Y, X = stdscr.getyx()
    s = []

    while True:
        c = stdscr.getch()

        if c in (13, 10):
            break
        elif c == ERASE:
            y, x = stdscr.getyx()
            if x > X:
                del s[-1]
                stdscr.move(y, (x - 1))
                stdscr.clrtoeol()
                stdscr.refresh()
        elif c in PRINTABLE:
            s.append(chr(c))
            stdscr.addch(c)

    return "".join(s)

def prompt(stdscr, y, x, prompt=">>> "):
    stdscr.move(y, x)
    stdscr.clrtoeol()
    stdscr.addstr(y, x, prompt)
    return input(stdscr)

def main(stdscr):
    Y, X = stdscr.getmaxyx()

    lines = []
    max_lines = (Y - 3)

    stdscr.clear()

    while True:
        s = prompt(stdscr, (Y - 1), 0)  # noqa
        if s == ":q":
            break

        # scroll
        if len(lines) > max_lines:
            lines = lines[1:]
            stdscr.clear()
            for i, line in enumerate(lines):
                stdscr.addstr(i, 0, line)

        stdscr.addstr(len(lines), 0, s)
        lines.append(s)

        stdscr.refresh()

wrapper(main)

这基本上设置了一个演示curses应用程序,它提示用户输入并在(24, 0)处显示提示。演示在用户输入:q时终止。对于任何其他输入,它会将输入附加到屏幕顶部。享受吧!(<BACKSAPCE>也可以!):)

请参见:curses;我在本例中使用的所有API都是直接来自这个标准库。虽然使用curse可能是也可能不是“过火”IHMO我建议使用urwid,特别是当你的应用程序的复杂性开始超过普通的咒语时。在

相关问题 更多 >