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

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

问题描述

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

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



ie控制台将打印:



移动文件:NameOfFile.txt

总进度:[########] 40%

解决方案

p>

然后在程序运行时适当更新

在Unix上,使用 curses 模块。



在Windows上,有以下几个选项:





使用curses的简单示例(我是总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,总进度:[{1:10}] {0}%。格式(进度* 10,#*进度) b $ b stdscr.refresh()

如果__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()


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()

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

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