Skip to main content
 首页 » 编程设计

python之如何用 Python 更新屏幕上的 N 行

2025年01月19日13xing901022

我已经生成了 N 个进程并监控它们的状态。所以,我想在屏幕上打印 N 行,每行的状态都在变化。

如何用 python 做到这一点?

我不想要可见的重印。是否有类似 tqdm 的库用于此类更新?

请您参考如下方法:

您可以使用几个终端转义码来做到这一点:

def up(lines=1): 
    clearline = '\033[2K' # clear a line 
    upline = '\033[1A'    # Move cursor up a line 
    for _ in range(lines): 
        sys.stdout.write(upline) 
        sys.stdout.write(clearline) 

在此之后您可以重新打印您的状态行。然后:

sys.stdout.flush() 

这是一个完整的工作程序来证明这一点:

import sys  
from time import sleep 
 
def up(lines=1): 
    clearline = '\033[2K' # clear a line 
    upline = '\033[1A'    # Move cursor up a line 
    for _ in range(lines): 
        sys.stdout.write(upline) 
        sys.stdout.write(clearline) 
 
num_lines = 3 
for i in range(10): 
    for l in range(num_lines): 
        sys.stdout.write('{} hello\n'.format(i*l+i)) 
    sys.stdout.flush() 
    sleep(0.5) 
    up(num_lines) 

当然,如果你正在制作一个完整的 tui,你会想要使用类似 curses 或 urwid 的东西。