在控制台中重写多行 [英] Rewrite multiple lines in the console

查看:64
本文介绍了在控制台中重写多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以用 \r一致地重写终端中显示的最后一行,但是我很难确定是否有办法返回并编辑控制台中打印的前几行。 / p>

我想做的是为基于文本的RPG重新打印多行,但是,对于一个应用程序有一行专用于进度栏,另一个描述下载。



ie控制台将打印:

 移动文件:NameOfFile.txt 
总进度:[ ########] 40%

,然后适当地(两行)更新为

解决方案

在Unix上,使用 curses 模块。



在Windows上,有几种选择:





使用诅咒的简单示例(我总共是诅咒n00b):

  import curses 
导入时间

def report_progress(文件名,进度):
进度:0-10
stdscr.addstr (0,0,正在移动文件:{0}。format(文件名))
stdscr.addstr(1,0,总进度:[{1:10}] {0}%。format(进度* 10,# *进度))
stdscr.refresh()

如果__name__ == __main__:
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()

试试:
for i in range(10):
report_progress( file_ {0} .txt .format(i),i + 1)
time.sleep(0.5)
最后:
curses.echo()
curses.nocbreak()
curses .endwin()


I know it is possible to consistently rewrite the last line displayed in the terminal with "\r", but I am having trouble figuring out if there is a way to go back and edit previous lines printed in the console.

What I would like to do is reprint multiple lines for a text-based RPG, however, a friend was also wondering about this for an application which had one line dedicated to a progress bar, and another describing the download.

i.e. the console would print:

Moving file: NameOfFile.txt  
Total Progress: [########              ] 40%

and then update appropriately (to both lines) as the program was running.

解决方案

On Unix, use the curses module.

On Windows, there are several options:

Simple example using curses (I am a total curses n00b):

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()

这篇关于在控制台中重写多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆