Python - 在控制台中重写多行 [英] Python - Rewrite multiple lines in the Console
问题描述
我知道有可能一致地用\r重写终端中显示的最后一行,但是我无法确定是否有办法返回并编辑控制台中打印的以前的行。 / p>
我想做的是为基于文本的RPG重新打印多行,但是一个朋友也想知道这个应用程序有一行专用于进度栏,另一个描述下载。
ie控制台将打印:
移动文件:NameOfFile.txt
总进度:[########] 40%
p>
然后在程序运行时适当更新
在Unix上,使用 curses 模块。
在Windows上,有以下几个选项:
- PDCurses:http://www.lfd.uci.edu/~gohlke/pythonlibs/
- 上面的HOWTO链接推荐了控制台模块
- http://newcenturycomputers.net/projects/wconio.html
- http://docs.activestate.com/activepython/2.7/pywin32/win32console.html
使用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:
- PDCurses: http://www.lfd.uci.edu/~gohlke/pythonlibs/
- The HOWTO linked above recommends the Console module
- http://newcenturycomputers.net/projects/wconio.html
- http://docs.activestate.com/activepython/2.7/pywin32/win32console.html
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屋!