I've noticed that a lot of command line tools, wget for example, will show progress as a number or progress bar that advances as a process is completed. While the question isn't really language-specific, out of the languages I use most often for command line tools (C++, Node.js, Haskell) I haven't seen a way to do this.
Here's an example, three snapshots of a single line of Terminal as wget downloads a file:
Along with other information, wget shows a progress bar (<=>) that advances as it downloads a file. The amount of data downloaded so far (6363, 179561, 316053) and the current download speed (10.7KB/s, 65.8KB/s, 63.0KB/s) update as well. How is this done?
Ideally, please include a code sample from one or more of the three languages mentioned above.
I can only speak about node.js, but the built-in
readline
module has some very basic screen handling functionality built-in. For example:There are also third party modules if you want to get fancier, such as
multimeter
/meterbox
andblessed
/blessed-contrib
.Generally speaking though, some programs use ncurses, while others simply just manually output the ANSI escape codes to clear and redraw the current line.
Looking at GNU wget repo on GitHub -- progress.c
It seems they do it the same way i.e. print a
\r
and then overwrite.Just print a CR (without a newline) to overwrite a line. Here is an example program in perl:
I've also disabled output buffering (
$| = 1
) so that the print command sends its output to the console immediately instead of buffering it.Haskell example:
They probably use the fancy ncurses library but on my
Linux
for my personal command-line tools I simply send'\r'
to move the cursor back to the start of the line to overwrite it with new progress information.