[Tutor] Displaying Status on the Command Line

Steven D'Aprano steve at pearwood.info
Wed Nov 7 18:00:51 EST 2018


On Wed, Nov 07, 2018 at 11:22:22AM -0500, Chip Wachob wrote:
> Hello,
> 
> I'm sure that this is simple and my searches have just not used the
> correct words.
> 
> What I would like to do is display, on a single line, in the terminal
> / command line a progress percentage, or, simply a sequence of - / -
> \, etc.. or even, accumulating period characters.
> 
> What would the escape codes be, or is there a better way to handle this?

Here's a quick and easy(?) way to do this which works on typical Linux 
systems. I've written it for Python 3, let us know if you need help 
getting it to work on Python 2.

import time
def spinner_demo():
    for i in range(1, 101):
        c = r'-\|/-\|/'[i % 8]
        print("Spinner:  %c %d%%\r" % (c, i), flush=True, end='')
        time.sleep(0.15)
    print('\n')


To display a throbber instead, change the first line inside the loop to 

        c = '.oOo'[i % 4]


Here's a progress bar:

def progress_demo():
    N = 250
    template = "Working hard... %- 40s %3.0f%% complete\r"
    for i in range(N):
        perc = i*100/N
        bar = '#'*(i*40//N + 1)
        print(template % (bar, perc), flush=True, end='')
        time.sleep(0.1)
    print('\n')


 
> Note that I need this to be platform agnostic.

That's hard, even on a single platform like Linux.

Most xterminal windows use either the xterm or vt1000 set of commands, 
which are broadly similar, but that's not guaranteed. If somebody 
happens to be running a different terminal type, they'll see something 
weird.

And I have no idea what happens on Windows.



-- 
Steve


More information about the Tutor mailing list