长话短说:
The
print()
result is not updating in a Windows Console. Executes fine in IDLE. Program is executing even though Windows Console is not updating.
背景
我有一个文件 test.py
包含:
编辑:包括我用来查看控制台是否正在更新的条件。最终,一系列 X
值再也不会在控制台中打印出来,并且控制台也不会向上滚动(就像在底部生成输出时通常所做的那样)。
count = 0
while True:
print ("True")
count += 1
if count == 10:
print ("XXXXXXXXX")
count = 0
当我在 cmd.exe
中运行它时,它显然会打印出大量的 True
。
然而,在运行大约 25 秒后,它不再打印,尽管程序仍在运行并且可以在任务管理器中看到。
我有一个程序,其中一些进度指示器最终停留在 50%,即使它们远远超过 50%,仅仅是因为 print()
没有显示在控制台输出中。
编辑:真正的用例问题。
上面的代码只是一个测试文件,用于查看控制台中的打印是否在所有程序中都停止了,而不是我正在运行的程序。实际上,我的程序打印到控制台,看起来像:
line [10] >> Progress 05%
第 [10] 行
不是真实的 但我只是在此处键入以向您展示 print()
发送到该行控制台窗口。随着我的程序的继续,它递增:
line [10] >> Progress 06%
line [10] >> Progress 11%
.
.
.
line [10] >> Progress 50%
每次 line [10]
都被覆盖。我使用 ANSI 转义字符和 colorama
相应地移动控制台光标:
print('\x1b[1000D\x1b[1A')
这会将光标向左移动 1000 列并向上移动 1 行(因此是上一行的开头)。
print("Progress "+ prog + "%")
不再出现在控制台中,因为最终执行了下一段 Python:
行 [11] >> 程序完成...
我验证了放入文件夹的结果。所以程序继续运行,而控制台没有更新。
编辑:这是运行stdout
更新的脚本。
def check_queue(q, dates, dct):
out = 0
height = 0
# print the initial columns and rows of output
# each cell has a unique id
# so they are stored in a dictionary
# then I convert to list to print by subscripting
for x in range(0, len(list(dct.values())), 3):
print("\t\t".join(list(dct.values())[x:x+3]))
height +=1 # to determine where the top is for cursor
while True:
if out != (len(dates) * 2):
try:
status = q.get_nowait()
dct[status[1]] = status[2]
print('\x1b[1000D\x1b[' + str(height + 1) + 'A')
# since there was a message that means a value was updated
for x in range(0, len(list(dct.values())), 3):
print("\t\t".join(list(dct.values())[x:x+3]))
if status[0] == 'S' or 'C' or 'F':
out += 1
except queue.Empty:
pass
else:
break
简而言之,我将一条消息从线程传递到队列。然后我更新了一个包含唯一单元 ID 的字典。我更新值,将控制台中的光标移动到打印列表的左上角位置,然后在其上打印。
问题:
When using stdout, is there a limit to how many times you can print to it in a period of time?
最佳答案
这很可能是一种错觉(可能是因为控制台中的行数有最大限制,然后新的行会替换第一行)。
您可以打印
的数量绝对没有限制。您可以使用每次迭代都会更改的内容来验证这一点,例如计算迭代次数的循环:
import itertools
for i in itertools.count():
print(i, "True")
关于python - 使用 print() 太多会导致它失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45574388/