我的 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")
Run Code Online (Sandbox Code Playgroud)
当只有 print 和 time.sleep 时, while 循环起作用。
while running:
print("Looping...")
time.sleep(5)
Run Code Online (Sandbox Code Playgroud)
当有该函数和 time.sleep 时,代码不起作用。
while running:
Write()
time.sleep(5)
Run Code Online (Sandbox Code Playgroud)
请告诉我如何解决这个问题。
我对你的发现感到困惑,现在找到了解决这个有趣行为的方法;您可以使用flush=True参数强制刷新:
import os\nimport time\n\nplace = 10\n\nrunning = True\n\ndef Write():\n j = 1\n for i in range(place - 1):\n print("-", end = "")\n j += 1\n print("a", end = "", flush=True)\n for k in range(10 - j):\n print("-", end = "", flush=True)\n\nwhile running:\n Write()\n time.sleep(1)\n if place > 1:\n place -= 1\n os.system("clear")\nRun Code Online (Sandbox Code Playgroud)\n\n\n输出是否缓冲通常由文件决定,但如果flush关键字参数为true,则强制刷新流。\xe2\x80\x94 https://docs.python.org/3/library/functions.html#打印
\n
或者,(i)将print()(不带end)放在 的末尾Write,或(ii)Write返回一个字符串(不在函数内部打印)并在函数外部(在循环中)打印字符串while似乎可行。评论部分绿斗篷家伙的解决方案,即,sys.stdout.flush()也有效。
在我看来,这end=\'\'使得 python 或控制台不愿意急切地显示字符(在某些情况下),等待一行结束。