tags:

views:

1549

answers:

5

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 of sorts that looks like this:

[======>                    ] 37%

and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?

+2  A: 

Commandline Progress bar

Prakash
+13  A: 

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.
}
hazzen
Assuming he's running a Win32 console app (not DOS) on a recent version of Windows (ie 2000+), ANSI escape codes won't work at all. As stated in the wikipedia article you linked to.
Hugh Allen
+16  A: 

One way to do this is to repeatedly update the line of text with the current progress. For example:

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

Note that I used sys.stdout.write instead of print (this is Python) because print automatically prints "\r\n" (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the flush() is necessary because by default, sys.stdout only flushes its output after a newline (or after its buffer gets full).

Greg Hewgill
And the same in 'c' with printf and '\r'.
David L Morris
+1  A: 

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

Steven Murawski
A: 

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...

Justin