How to animate the command line?

前端 未结 8 1857
臣服心动
臣服心动 2020-11-27 09:09

I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar

相关标签:
8条回答
  • 2020-11-27 09:44

    PowerShell has a Write-Progress cmdlet that creates an in-console progress bar that you can update and modify as your script runs.

    0 讨论(0)
  • 2020-11-27 09:49

    below is my answer,use the windows APIConsoles(Windows), coding of 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;
    }
    
    0 讨论(0)
  • If your using a scripting language you could use the "tput cup" command to get this done... P.S. This is a Linux/Unix thing only as far as I know...

    0 讨论(0)
  • 2020-11-27 09:54

    As a follow up to Greg's answer, here is an extended version of his function that allows you to display multi-line messages; just pass in a list or tuple of the strings you want to display/refresh.

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

    Note: I have only tested this using a linux terminal, so your mileage may vary on Windows-based systems.

    0 讨论(0)
  • 2020-11-27 09:56

    There are two ways I know of to do this:

    • Use the backspace escape character ('\b') to erase your line
    • Use the curses package, if your programming language of choice has bindings for it.

    And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:

    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.
    }
    
    0 讨论(0)
  • 2020-11-27 10:00

    The secret is to print only \r instead of \n or \r\n at the and of the line.

    \r is called carriage return and it moves the cursor at the start of the line

    \n is called line feed and it moves the cursor on the next line In the console. If you only use \r you overwrite the previously written line. So first write a line like the following:

    [          ]
    

    then add a sign for each tick

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

    and so on. You can use 10 chars, each representing a 10%. Also, if you want to display a message when finished, don't forget to also add enough white chars so that you overwrite the previously written equal signs like so:

    \r[done      ]
    
    0 讨论(0)
提交回复
热议问题