如何为命令行设置动画?
时间:2020-03-05 18:52:37 来源:igfitidea点击:
我一直想知道人们如何在命令行中更新上一行。一个很好的例子是在Linux中使用wget命令时。它会创建如下所示的ASCII加载条:
[======> ] 37%
当然,加载栏会移动,百分比也会发生变化,但是不会产生新的变化。我不知道该怎么做。有人可以指出我正确的方向吗?
解决方案
回答
我知道有两种方法可以做到这一点:
- 使用退格转义符('\ b')删除行
- 如果我们选择的编程语言具有绑定,请使用
curses
软件包。
谷歌透露了ANSI转义码,这似乎是个好方法。作为参考,下面是C ++中的一个函数:
void DrawProgressBar(int len, double percent) { cout << "\x1B[2K"; // Erase the entire current line. cout << "\x1B[0E"; // Move to the beginning of the current line. string progress; for (int i = 0; i < len; ++i) { if (i < static_cast<int>(len * percent)) { progress += "="; } else { progress += " "; } } cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%"; flush(cout); // Required. }
回答
一种方法是使用当前进度重复更新文本行。例如:
def status(percent): sys.stdout.write("%3d%%\r" % percent) sys.stdout.flush()
请注意,我使用sys.stdout.write而不是print(这是Python),因为print在每一行的末尾自动打印" \ r \ n"(回车换行)。我只希望将光标返回到行首的回车。同样,flush()
是必需的,因为默认情况下,sys.stdout
仅在换行符之后(或者其缓冲区已满)刷新其输出。
回答
PowerShell具有一个Write-Progress cmdlet,该cmdlet创建一个控制台中进度条,我们可以在脚本运行时对其进行更新和修改。
回答
如果我们使用脚本语言,则可以使用" tput cup"命令来完成此操作...
P.S.据我所知,这是Linux / Unix问题。