Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why python don't print after a time.sleep()?

I'm programming in python for almost 2 years and I found a really weird thing when watching some old code.

import random, sys, time

try:
    while True:
        print(' ', str(random.randint(100,999)), end='')
        time.sleep(0.01)
except:
    sys.exit()

Following the syntax of this code my program should print a space and a random number from 100 to 999 forever, but this isn't happening.

When I run this code nothing appear on the screen until I press CTRL-C, even removing the try statement din't change anything.

I tried changing console (Windows terminal, powershell and CMD) but nothing happened.

Can please someone help me out with this? Thanks

like image 912
user187624 Avatar asked Nov 15 '19 19:11

user187624


People also ask

How does the sleep function work in Python?

The sleep() function suspends execution of the current thread for a given number of seconds. In case of single-threaded programs, sleep() suspends execution of the thread and process. However, the function suspends a thread rather than the whole process in multithreaded programs.

How do I set a sleep timer in Python?

Adding a Python sleep() Call With time.sleep() Python has built-in support for putting your program to sleep. The time module has a function sleep() that you can use to suspend execution of the calling thread for however many seconds you specify.

How do you delay printing in Python?

Make your time delay specific by passing a floating point number to sleep() . from time import sleep print("Prints immediately.") sleep(0.50) print("Prints after a slight delay.")


1 Answers

Python keeps your print outputs in a buffer and waits for the end of the line before actually displaying it. To force the display in Python 3, you can add the keyword flush=True.

import random, sys, time

try:
    while True:
        print(' ', str(random.randint(100,999)), end='', flush=True)
        time.sleep(0.01)
except:
    sys.exit()

Alternatively, you can:

  • call sys.stdout.flush() after the print (Python 2-compatible);
  • use the -u flag when executing the script (python -u script.py);
  • set the environment variable PYTHONUNBUFFERED to TRUE.
like image 182
Antoine Dujardin Avatar answered Sep 28 '22 14:09

Antoine Dujardin