Jazz Up Your CLI with Progress Tracking
I have a BeanShell script that takes a few minutes to run. I wanted to provide some feedback on the progress to the user.
The JUnit text UI tracks progress by printing a series of dots, one per test. This works fine for a relatively small and fixed number of items like unit tests, but in my case, the number of items is much larger and variable. When I tried this approach with my script, the dots scrolled off of the screen, and as a user, I really had no idea how many dots to expect.
$ java junit.textui.TestRunner ......................................... ......................................... ............................ Time: 2.609 OK (110 tests)
I decided I wanted to print out the percentage of completion in place; the current percentage should overwrite the previous value. I accomplished this using the backspace character '\b':
print(s) {
System.out.print(s);
}
/**
* Print percentage, where "percent" is between 0 and 100.
*/
printPercent(int percent) {
// clear previous value.
print("\b\b\b\b");
if (percent < 10)
print(" ");
if (percent < 100)
print(" ");
print(percent);
print("%");
}
If I want to get fancy, I can further enhance the script and print out an estimated time to completion. One caveat, special characters play nicely with terminals, but not so when you redirect output to a file.
- Login or register to post comments
- Printer-friendly version
- crazybob's blog
- 610 reads





