如何为命令行设置动画?

时间:2008-09-13 00:53:11

标签: command-line

我一直想知道人们如何更新命令行中的上一行。一个很好的例子是在linux中使用wget命令。它会创建一个类似于此的ASCII加载栏:

  

[==> ] 37%

当然加载栏会移动并且百分比会发生变化,但它不会成为新的一行。我无法弄清楚如何做到这一点。有人能指出我正确的方向吗?

8 个答案:

答案 0 :(得分:56)

执行此操作的一种方法是使用当前进度重复更新文本行。例如:

def status(percent):
    sys.stdout.write("%3d%%\r" % percent)
    sys.stdout.flush()

请注意,我使用了sys.stdout.write而不是print(这是Python),因为print会在结尾处自动打印“\ r \ n”(回车换行)每一行。我只想要回车,它将光标返回到行的开头。此外,flush()是必需的,因为默认情况下,sys.stdout仅在换行符之后(或在其缓冲区变满之后)刷新其输出。

答案 1 :(得分:42)

我知道有两种方法可以做到这一点:

  • 使用退格符转义符('\ b')删除行
  • 如果您选择的编程语言具有绑定,请使用curses包。

Google透露ANSI Escape Codes,这似乎是一个好方法。作为参考,这是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.
}

答案 2 :(得分:16)

秘诀是只打印\ r而不是\ n或\ r \ n在该行的行。

\ r被称为回车,它将光标移动到行的开头

\ n称为换行,它将光标移动到下一行 在控制台中。如果您只使用\ r,则覆盖以前写入的行。 所以首先写一行如下:

[          ]

然后为每个刻度添加一个符号

\r[=         ]

\r[==        ]

...

\r[==========]

等等。 你可以使用10个字符,每个字符代表10%。 此外,如果您想在完成时显示消息,请不要忘记添加足够的白色字符,以便覆盖以前写过的等号,如下所示:

\r[done      ]

答案 3 :(得分:4)

下面是我的回答,使用Windows API Consoles(Windows),C编码。

/*
* file: ProgressBarConsole.cpp
* description: a console progress bar Demo
* author: lijian <hustlijian@gmail.com>
* version: 1.0
* date: 2012-12-06
*/
#include <stdio.h>
#include <windows.h>

HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO bInfo;
char charProgress[80] = 
    {"================================================================"};
char spaceProgress = ' ';

/*
* show a progress in the [row] line
* row start from 0 to the end
*/
int ProgressBar(char *task, int row, int progress)
{
    char str[100];
    int len, barLen,progressLen;
    COORD crStart, crCurr;
    GetConsoleScreenBufferInfo(hOut, &bInfo);
    crCurr = bInfo.dwCursorPosition; //the old position
    len = bInfo.dwMaximumWindowSize.X;
    barLen = len - 17;//minus the extra char
    progressLen = (int)((progress/100.0)*barLen);
    crStart.X = 0;
    crStart.Y = row;

    sprintf(str,"%-10s[%-.*s>%*c]%3d%%", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);
#if 0 //use stdand libary
    SetConsoleCursorPosition(hOut, crStart);
    printf("%s\n", str);
#else
    WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);
#endif
    SetConsoleCursorPosition(hOut, crCurr);
    return 0;
}
int main(int argc, char* argv[])
{
    int i;
    hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hOut, &bInfo);

    for (i=0;i<100;i++)
    {
        ProgressBar("test", 0, i);
        Sleep(50);
    }

    return 0;
}

答案 4 :(得分:3)

PowerShell有一个Write-Progress cmdlet,可以创建一个控制台进度条,您可以在脚本运行时更新和修改它。

答案 5 :(得分:3)

以下是您的问题的答案......(python)

def disp_status(timelapse, timeout):
  if timelapse and timeout:
     percent = 100 * (float(timelapse)/float(timeout))
     sys.stdout.write("progress : ["+"*"*int(percent)+" "*(100-int(percent-1))+"]"+str(percent)+" %")
     sys.stdout.flush()
     stdout.write("\r  \r")

答案 6 :(得分:2)

作为Greg's answer的后续,这是他的功能的扩展版本,允许您显示多行消息;只需传入要显示/刷新的字符串的列表或元组。

def status(msgs):
    assert isinstance(msgs, (list, tuple))

    sys.stdout.write(''.join(msg + '\n' for msg in msgs[:-1]) + msgs[-1] + ('\x1b[A' * (len(msgs) - 1)) + '\r')
    sys.stdout.flush()

注意:我之前只使用过Linux终端对其进行了测试,因此基于Windows的系统的里程可能会有所不同。

答案 7 :(得分:0)

如果您使用脚本语言,可以使用“tput cup”命令完成此操作... 附:据我所知,这只是一个Linux / Unix的东西......