我正在尝试在处理大量数据的生成器内打印调试信息。但是,只有当生成器完成时我才能看到结果。
我使用的是python 3,我的代码如下:
def generator():
while 1:
print ('.', end='')
time.sleep(1)
yield 1
for a in generator():
print ('|', end='')
Result:
^C.|.|.|.|.|
等效的 PHP7 代码按预期工作:
function generator()
{
while (1) {
echo '.';
sleep(1);
yield 1;
}
}
foreach (generator() as $item) {
echo '|';
}
Result:
.|.|.|.|.|^C
如何为生成器周期的每次迭代实时打印调试信息?
TL;DR:
我相信您也有与该问题类似的问题:调用serve_forever() 时打印语句不起作用? https://stackoverflow.com/questions/43197518/print-statements-not-working-when-serve-forever-is-called/43250818#43250818(虽然从标题上看不出来……)
尝试冲洗您的指纹:
print ('.', end='', flush=True)
print ('|', end='', flush=True)
flush
方法flush()刷新内部缓冲区,就像stdio 的刷新 https://www.tutorialspoint.com/c_standard_library/c_function_fflush.htm。这对于某些类似文件的对象可能是无操作的。
It forces the print()
函数打印到目前为止已缓冲的内容stdout
您的机器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)