Python loop keeps stopping in Window's interpreter

Viewed 291

I'm using the default Python 3.8 interpreter in Windows.

Whenever I run a long loop in it, it'll stop and I have to press or hold down the Enter key for it to keep going. This was never a problem in Linux.

How do I fix this behavior?

# this loop will eventually stop/hang/pause forever, until I press the Enter key
for i in range(5000):
   time.sleep(1)
   print(i)

If I run the code through any IDE, it doesn't pause. But I want to run this particular code directly in the interpreter for my own reasons.

I took this screenshot after waiting more than 1 minute for it to continue. This isn't a once off problem. ANY loop I run, no matter how small or big or complex, will permanently stop after a few iterations until I press the ENTER key on my keyboard.

enter image description here

enter image description here

enter image description here

3 Answers

The program you have shown will literally do nothing. It won't print anything to console and doesn't wait for input.

So it will literally run for 83 minutes not showing that it is doing anything and then it will exit with a exit code of 0.

The console will pause the script if you click on the output, it will try to stop the code to "select" a part of the output. give it a try without clicking it. ENTER will remove focus from the select bar on the console, so you will see that the it's not there anymore.

I have a guess at what you are running into.

Of course, the program continues to run, but you just did not see the output, because the output is buffered and you don't flush it.

So, after each print(i), call the function flush_output_streams():

def flush_output_streams() -> None:
    """
    flushes the output streams.

    flush calls are wrapped in try ... except, because 
    standard streams might be replaced with other streams which 
    dont have the flush method.
    """
    try:
        sys.stdout.flush()
    except Exception:
        pass
    try:
        sys.stderr.flush()
    except Exception:
        pass
Related