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
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.
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.
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.")
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:
sys.stdout.flush()
after the print (Python 2-compatible);-u
flag when executing the script (python -u script.py
);PYTHONUNBUFFERED
to TRUE
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With