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(ran
Solution 1:
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 
-uflag when executing the script (python -u script.py); - set the environment variable 
PYTHONUNBUFFEREDtoTRUE. 
Solution 2:
This answer Python sleep() inhibit print with comma? suggests adding sys.stdout.flush() between the print and the sleep. Tested it - works.
Solution 3:
Which version of PYTHON are you using? I was able to run your code in my PC where I am using PYTHON 3.7 in PYCHARM 2019.2.4. It also ran successfully on PYTHON 3.7.5 shell
Solution 4:
Try this:
import random, sys, time
try:
    while True:
        print(' ', str(random.randint(100,999)), end='', flush=True)
        time.sleep(1)
except:
    sys.exit()
Solution 5:
This is because you have a while True clause that's looping forever, Causing it loop recursively infinitely.
Here is the updated code
import random, sys, time
try:
    whileTrue:
        print(' ', str(random.randint(100,999)), end='')
        time.sleep(0.01)
        breakexcept:
    sys.exit()
I added a break statement to move to get out of the loop.
Post a Comment for "Why Python Don't Print After A Time.sleep()?"