【发布时间】:2009-11-13 04:38:40
【问题描述】:
我知道要更新命令行上的进度条之类的东西,可以使用“\r”。有没有办法更新多行?
【问题讨论】:
我知道要更新命令行上的进度条之类的东西,可以使用“\r”。有没有办法更新多行?
【问题讨论】:
如果您使用的是 Python,请尝试使用 blessings。这是一个非常直观的诅咒包装。
简单示例:
from blessings import Terminal
term = Terminal()
with term.location(0, 10):
print("Text on line 10")
with term.location(0, 11):
print("Text on line 11")
如果您实际上是在尝试实现进度条,请考虑使用
progressbar。它将为您节省很多\r cruft。
您实际上可以将祝福和进度条连接在一起。尝试运行:
import time
from blessings import Terminal
from progressbar import ProgressBar
term = Terminal()
class Writer(object):
"""Create an object with a write method that writes to a
specific place on the screen, defined at instantiation.
This is the glue between blessings and progressbar.
"""
def __init__(self, location):
"""
Input: location - tuple of ints (x, y), the position
of the bar in the terminal
"""
self.location = location
def write(self, string):
with term.location(*self.location):
print(string)
writer1 = Writer((0, 10))
writer2 = Writer((0, 20))
pbar1 = ProgressBar(fd=writer1)
pbar2 = ProgressBar(fd=writer2)
pbar1.start()
pbar2.start()
for i in range(100):
pbar1.update(i)
pbar2.update(i)
time.sleep(0.02)
pbar1.finish()
pbar2.finish()
【讨论】:
progressbar的当前版本希望文件句柄也有flush()方法。
最好的方法是使用一些现有的库,比如 ncurses。但是您可以通过使用系统调用清除控制台来尝试肮脏的解决方法:system("cls");。
【讨论】:
您可以使用VT100 codes 将光标重新定位到更高的行,然后使用更新后的状态覆盖它。
【讨论】:
Curses 库为控制台 UI 提供了强大的控制。
【讨论】: