Welcome, guest | Sign In | My Account | Store | Cart

This recipe has a similar objective to http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473899, but was not derived from it. This recipe was written before the aforementioned recipe was submitted to this Cookbook. The purpose of this demo is to illustrate showing the status of an operation to a user in an ASCII environment.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import os, time

def main():
    status, key = 0, ['|', '/', '-', '\\']
    while True:
        os.system('cls')
        print '.' * (status / 8) + key[status % 4]
        status += 1
        time.sleep(0.1)

if __name__ == '__main__':
    main()

This recipe can easily be modified to run Linux (as it is meant to run on Windows) and can even be modified to run on either Windows or Linux (as one program). The main feature of this recipe is its approach to clearing the screen. Finally, "main" can be run in a thread while another thread is actually doing some work. This is demonstrated in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473881 through function "__working".

2 comments

Matthieu Walter 18 years, 1 month ago  # | flag

Improvement. I'd prefere to get rid of that os.system call by doing

import time, sys

def main():
    status, key = 0, ['|', '/', '-', '\\']
    while True:
        print '.' * (status / 8) + key[status % 4] + '\r',
        sys.stdout.flush()
        status += 1
        time.sleep(0.1)

if __name__ == '__main__':
    main()
Thanasis Stamos 18 years, 1 month ago  # | flag

Themes.

The list of strings is a bit artificial. Plain string will do the job just as well.
The print command adds an extra space. sys.stdout.write does
not have this problem.
Finally the recipy may be themable! Try the themes below.
(No I will not test the code in WinDoze)

#! /usr/local/bin/python
import time, sys

rotor  = "|/-\\|/-\\"
baloon = " .oO@@Oo. "
square = " _uUOOUu_ "
dash   = "_-=##=-_ "
rotor2 = "3WEM"
w = sys.stdout.write; f = sys.stdout.flush

def main(them):
    status = 0; n = len(them); n2 = 3*n
    while True:
        w(them[status % n]); f()
        time.sleep(0.1)
        status += 1
    if not (status%n2): w('\b.')
    else:               w('\b')

if __name__ == '__main__':
#    main(rotor)
    main(baloon)
#    main(square)