Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions LoadingIcon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

# Loading Icon

When doing a lengthy calculation, instead of staring at a blank screen, the program runs a spinner to show that it's still working.
In the threading example the spinner is running in a different thread, in the async example, the spinner is another task in the event loop.
43 changes: 43 additions & 0 deletions LoadingIcon/async_spinner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import asyncio
import itertools
import sys


async def spin(msg):
write, flush = sys.stdout.write, sys.stdout.flush

for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))

try:
await asyncio.sleep(0.1)
except asyncio.CancelledError:
break

write(' ' * len(status) + '\x08' * len(status))


async def slow_function():
await asyncio.sleep(5)
return 42


async def supervisor():
spinner = asyncio.ensure_future(spin('Thinking!'))
result = await slow_function()
spinner.cancel()
return result


def main():
loop = asyncio.get_event_loop()
result = loop.run_until_complete(supervisor())
loop.close()
print('Answer:', result)


if __name__ == '__main__':
main()
49 changes: 49 additions & 0 deletions LoadingIcon/threading_spinner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@

import threading
import itertools
import time
import sys


class Signal:
go = True


def spin(msg, signal):
write, flush = sys.stdout.write, sys.stdout.flush

for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))
time.sleep(0.1)

if not signal.go:
break

write(' ' * len(status) + '\x08' * len(status))


def slow_function():
time.sleep(5)
return 42


def supervisor():
signal = Signal()
spinner = threading.Thread(target=spin, args=('thinking!', signal))
spinner.start()
result = slow_function()
signal.go = False
spinner.join()
return result


def main():
result = supervisor()
print('Answer:', result)


if __name__ == '__main__':
main()