每一行都在终端+一些固定的文本

Terminal with each line after another + some fixed text as well

我两个都想要:

几乎 有效,直到 ~ 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 cmd.exe 中获得 ANSI 支持。

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

如果您对 movePos 的调用在 ansicon 的工作范围内space,您会得到更一致的结果。

关于"Bonjour"的"multiple lines",这个块

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

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

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

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

这是一个解决方案:


(来源: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)