一行接一行的终端+一些固定的文本

2024-05-29 11:26:59 发布

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

我想要两种:

  • 像在普通终端中一样,一行接一行地显示(Blah 12、Blah 13、Blah 14等)

  • 固定位置信息(右侧):日期+固定文本“Bonjour”

它几乎是有效的,直到~Blah 250,当外观被摧毁!为什么?在


(来源:gget.it

from sys import stdout
import time

ESC = "\x1b"
CSI = ESC+"["

def movePos(row, col):
    stdout.write("%s%d;%dH" % (CSI, row, col))

stdout.write("%s2J" % CSI)      # CLEAR SCREEN

for i in range(1,1000):
    movePos(i+1,60)
    print time.strftime('%H:%M:%S', time.gmtime())
    movePos(i+5,60)
    print 'Bonjour'

    movePos(24+i,0)
    print "Blah %i" % i
    time.sleep(0.01)

对于ANSI终端,如何同时具有正常的终端行为(每个print)和固定位置显示?

注意:在Windows上,我使用ansicon.exe文件在Windows中支持ANSI命令提示符.


Tags: import终端timewindowsstdoutcolwriterow
2条回答

这里有一个解决方案:


(来源:gget.it

代码是(检查here以获取最新版本):

"""
zeroterm is a light weight terminal allowing both:
* lines written one after another (normal terminal/console behaviour)
* fixed position text

Note: Requires an ANSI terminal. For Windows 7, please download https://github.com/downloads/adoxa/ansicon/ansi160.zip and run ansicon.exe -i to install it.
"""

from sys import stdout
import time

class zeroterm:
    def __init__(self, nrow=24, ncol=50):      # nrow, ncol determines the size of the scrolling (=normal terminal behaviour) part of the screen
        stdout.write("\x1b[2J")                # clear screen
        self.nrow = nrow
        self.ncol = ncol
        self.buf = []

    def write(self, s, x=None, y=None):        # if no x,y specified, normal console behaviour
        if x is not None and y is not None:    # if x,y specified, fixed text position
            self.movepos(x,y)
            print s
        else:
            if len(self.buf) < self.nrow:
                self.buf.append(s)
            else:
                self.buf[:-1] = self.buf[1:]
                self.buf[-1] = s

            for i, r in enumerate(self.buf):
                self.movepos(i+1,0)
                print r[:self.ncol].ljust(self.ncol)

    def movepos(self, row, col):
        stdout.write("\x1b[%d;%dH" % (row, col))


if __name__ == '__main__':
    # An exemple
    t = zeroterm()
    t.write('zeroterm', 1, 60)

    for i in range(1000):
        t.write(time.strftime("%H:%M:%S"), 3, 60)
        t.write("Hello %i" % i)
        time.sleep(0.1)

从给定的图片来看:ansicon似乎在分配一个控制台缓冲区来完成它的工作;这个缓冲区的大小是有限的(由于Windows控制台将缓冲区大小限制为64KB)。一旦脚本到达缓冲区的末尾并试图将光标移过缓冲区的末尾,ansicon会强制整个缓冲区向上滚动。这就改变了更新的风格。在

如果您对movePos的调用是在ansicon的工作区内进行的,那么您将得到更加一致的结果。在

关于“Bonjour”的“多行”,这一块

movePos(i+1,60)
print time.strftime('%H:%M:%S', time.gmtime())
movePos(i+5,60)
print 'Bonjour'

是在一行上打印日期,然后向前移动4行,在同一列上打印“Bonjour”。在同一行上似乎有足够的空间(10列)来执行此操作:

^{pr2}$

这至少能让右边的文字看起来一致。但是,从movePos滚动时,有时会导致一些双间距。在

相关问题 更多 >

    热门问题