5

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

Shahriar Rahman Zahin
  • 624
  • 1
  • 11
  • 23
user187624
  • 71
  • 1
  • 1
  • 8

5 Answers5

6

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.
5

This answer Python sleep() inhibit print with comma? suggests adding sys.stdout.flush() between the print and the sleep. Tested it - works.

Iliyan Bobev
  • 3,070
  • 2
  • 20
  • 24
0

Try this:

import random, sys, time
try:
    while True:
        print(' ', str(random.randint(100,999)), end='', flush=True)
        time.sleep(1)
except:
    sys.exit()
Akshay G Bhardwaj
  • 339
  • 1
  • 4
  • 14
0

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

Shahriar Rahman Zahin
  • 624
  • 1
  • 11
  • 23
-1

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:
    while True:
        print(' ', str(random.randint(100,999)), end='')
        time.sleep(0.01)
        break
except:
    sys.exit()

I added a break statement to move to get out of the loop.

Salman Farsi
  • 466
  • 3
  • 13