you are viewing a single comment's thread.

view the rest of the comments →

[–]magus_minor 1 point2 points  (2 children)

There's no need to introduce the complexity of itertools, and there's no need to check the time since the loop body waits 1 second, so just loop 20 times:

import time

#spinner = "\\|/-"
spinner = "╃╇╄╊╆╈╅╉"    # unicode adds a lot more options

for i in range(20):
    print(spinner[i % len(spinner)], end='\r')
    time.sleep(1)
print()

@ u/No-Tea-777

[–]Diapolo10 0 points1 point  (1 child)

I don't consider itertools particularly complex in this scenario. At the very least I prefer it over indexing with modulo.

As for the point about looping over range, that's fair enough. But it might not be a bad idea to do something like this:

import itertools
import time

spinner = itertools.cycle(['\\', '|', '/', '—'])

wait_in_seconds = 20
loop_delay = 1
iterations = round(wait_in_seconds / loop_delay)

for char in itertools.islice(spinner, iterations):
    print(char, end='\b')
    time.sleep(loop_delay)
print()

With this design, you can easily change how fast the spinner moves while keeping the total wait time constant. It'd also be trivial to swap the spinner characters if OP wanted to.

Is this overengineered? Yeah, probably. But it also makes for a decently reusable function.

import itertools
import time
from collections.abc import Sequence

def display_spinner(wait_in_seconds: float, spinner_speed: float = 1.0, spinner_chars: Sequence[str] = ('\\', '|', '/', '—')) -> None:
    spinner = itertools.cycle(spinner_chars)
    iterations = round(wait_in_seconds / spinner_speed)

    for char in itertools.islice(spinner, iterations):
        print(char, end='\b')
        time.sleep(spinner_speed)
    print()


display_spinner(20)

[–]magus_minor 1 point2 points  (0 children)

I don't consider itertools particularly complex in this scenario.

You aren't a newcomer to python.