Created
October 2, 2020 06:50
-
-
Save victor-iyi/a90fb82bb51f9e447cc609e65d4b6e74 to your computer and use it in GitHub Desktop.
A spinner function as a visual aid for processing long computation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import time | |
| import multiprocessing as mp | |
| DELAY = 0.1 | |
| DISPLAY = ['|', '/', '-', '\\'] | |
| def spinner_fn(before='', after=''): | |
| write, flush = sys.stdout.write, sys.stdout.flush | |
| pos = -1 | |
| while True: | |
| pos = (pos + 1) % len(DISPLAY) | |
| msg = before + DISPLAY[pos] + after | |
| write(msg); flush() | |
| write('\x08' * len(msg)) | |
| time.sleep(DELAY) | |
| def long_computation(): | |
| # Emulate a long computation. | |
| time.sleep(3) | |
| if __name__ == '__main__': | |
| spinner = mp.Process(None, spinner_fn, | |
| args=('Please wait ...', '')) | |
| spinner.start() | |
| try: | |
| long_computation() | |
| print('\nComputation done') | |
| finally: | |
| spinner.terminate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment