Timothy Waters
Timothy Waters

Reputation: 73

How to stop function executing before being called in Python 3

I am porting a C++ program I wrote for no good reason to Python 3. There is a spinner() function that uses a spin() function. These display a banner at the top of the program. However, for some reason I can't figure out, the spin() function is being executed before being called. Also the sleep(1) is being executed before being called as well. I can't figure out why these are being executed before being called. It currently executes the sleep() function then the spin() function before ever being called. They shouldn't execute until after the first array item is displayed.

I have tried putting the spin() and sleep() functions in different spots to try and troubleshoot where it is getting called from, but doing so breaks the current functionality.

import time
import sys

def spin():
    spinner = ['/', '-', '\\', '|', '']
    for i in spinner:
        sys.stdout.write(i)
    time.sleep(1)
    sys.stdout.write("\b")
    sys.stdout.flush()

def spinner():
    text = "\tVigenere Cipher\n"
    textArray = list(text)
    for i in range(len(textArray)):
        for x in range(i):
        sys.stdout.write(textArray[x])
    spin()
    sys.stdout.write("\r")
    sys.stdout.flush()
spinner()

I expect it to print a character from textArray, show the spinner, print the next character, show the spinner, etc.

The actual results are that it first sleeps, prints the spinner, then prints the first character.

Upvotes: 1

Views: 597

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

You need to call sys.stdout.flush() before the sleep, not after. flush is the magic that forces the text from buffer to screen, and doing it after the sleep means you (usually; buffering is an implementation detail) won't see anything until the sleep completes.

Upvotes: 2

Related Questions