简体   繁体   中英

While Loop Not Working (Function and Time.Sleep)

My while loop prints nothing when it is running.

import os
import time

place = 10

running = True

def Write():
  j = 1
  for i in range(place - 1):
    print("-", end = "")
    j += 1
  print("a", end = "")
  for k in range(10 - j):
    print("-", end = "")

while running:
  Write()
  time.sleep(5)
  if place > 1:
    place -= 1
  os.system("clear")

When there is just the print and a time.sleep, the while loop works.

while running:
  print("Looping...")
  time.sleep(5)

When there is the function and a time.sleep, the code doesn't work.

while running:
  Write()
  time.sleep(5)

Please tell me how to fix this.

I got puzzled by what you discovered, and now found a solution to this interesting behavior; you can use flush=True parameter to force flushing:

import os
import time

place = 10

running = True

def Write():
  j = 1
  for i in range(place - 1):
    print("-", end = "")
    j += 1
  print("a", end = "", flush=True)
  for k in range(10 - j):
    print("-", end = "", flush=True)

while running:
  Write()
  time.sleep(1)
  if place > 1:
    place -= 1
  os.system("clear")

Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.— https://docs.python.org/3/library/functions.html#print

Alternatively, (i) putting print() (without end ) at the end of Write , or (ii) making Write to return a string (not print inside the function) and printing the string outside the function (in the while loop) seems to work. Green Cloak Guy's solution in the comment section, ie, sys.stdout.flush() works too.

It seems to me that end='' makes python or console reluctant to show the characters eagerly (in some cases), waiting for a line to end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM