简体   繁体   English

While 循环不工作(函数和 Time.Sleep)

[英]While Loop Not Working (Function and Time.Sleep)

My while loop prints nothing when it is running.我的 while 循环在运行时不打印任何内容。

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.当只有 print 和 time.sleep 时,while 循环起作用。

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

When there is the function and a time.sleep, the code doesn't work.当有函数和 time.sleep 时,代码不起作用。

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:您可以使用flush=True参数强制刷新:

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输出是否缓冲通常由文件决定,但如果flush关键字参数为真,则流被强制刷新。— 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.或者,(i)将print() (没有end )放在Write的末尾,或者(ii)使Write返回一个字符串(不在函数内部打印)并在函数外部打印字符串(在while循环中)似乎去工作。 Green Cloak Guy's solution in the comment section, ie, sys.stdout.flush() works too. Green Cloak Guy 在评论部分的解决方案,即sys.stdout.flush()也有效。

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.在我看来, end=''使 python 或控制台不愿意急切地显示字符(在某些情况下),等待一行结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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