如何在结束循环之前查看发生器的打印输出? [英] How to see print output from generator before ending the cycle?
问题描述
我正在尝试在包含大量数据的生成器中打印调试信息.但是,只有在生成器完成后,我才能看到结果.
I'm trying to print debug information inside a generator working with big list of data. But, I can see the result only when the generator finishes.
我正在使用python 3,我的代码如下:
I am using python 3 and my code is as follows:
def generator():
while 1:
print ('.', end='')
time.sleep(1)
yield 1
for a in generator():
print ('|', end='')
结果:
^C.|.|.|.|.|
等效的PHP7代码按预期工作:
Equivalent PHP7 code works as expected:
function generator()
{
while (1) {
echo '.';
sleep(1);
yield 1;
}
}
foreach (generator() as $item) {
echo '|';
}
结果:
.|.|.|.|.|^C
如何在生成器周期的每次迭代中实时打印调试信息?
How to print debug information in realtime for each iteration of the generator's cycle?
推荐答案
TL; DR:
I believe that you have a similar issue to that question: Print statements not working when serve_forever() is called? (although by the title is not apparent...)
尝试冲洗您的照片:
print ('.', end='', flush=True)
print ('|', end='', flush=True)
冲洗
flush()方法刷新内部缓冲区,例如 stdio的刷新.对于某些类似文件的对象,这可能是空话.
The method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.
它强制将print()
功能打印到该点为止的任何内容缓存到计算机的stdout
.
It forces the print()
function to print whatever have been buffered up to that point to the stdout
of your machine.
这篇关于如何在结束循环之前查看发生器的打印输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!