python实时打印功能
我最近更换了操作系统并使用更新的 Python (2.7)。在我的旧系统上,我曾经能够即时打印。例如,假设我有一个计算密集型的 for 循环:
for i in range(10):
huge calculation
print i
然后当代码完成每次迭代时,它会打印 i
但是,在我当前的系统上,python 似乎缓存了 stdout,因此终端是空白的几分钟,然后打印:
1 2 3
in short succession.然后,又过了几分钟,它打印:
4 5 6
等等。如何让 python 在到达 print
语句时立即打印?
I recently switched OS and am using a newer Python (2.7). On my old system, I used to be able to print instantaneously. For instance, suppose I had a computationally intense for loop:
for i in range(10):
huge calculation
print i
then as the code completed each iteration, it would print i
However, on my current system, python seems to cache the stdout so that the terminal is blank for several minutes, after which it prints:
1 2 3
in short succession. Then, after a few more minutes, it prints:
4 5 6
and so on. How can I make python print as soon as it reaches the print
statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在打印后调用 stdout 的刷新
或使用 命令行 选项 -u 其中:
Try to call flush of stdout after the print
Or use a command line option -u which:
从Python 3.3开始,您可以简单地将 flush=True 传递给 print 函数。
Since Python 3.3, you can simply pass flush=True to the print function.
导入新的 print-as-function 如 Python 3.x 中所示:
(将语句放在脚本/模块的顶部)
这允许您用自己的打印函数替换新的打印函数:
优点是这样您的脚本升级后效果会一样总有一天会到 Python 3.x。
Ps1:我没有尝试过,但 print-as-function 可能会默认刷新。
PS2:您可能也对我的 进度条示例。
Import the new print-as-function as in Python 3.x:
(put the statement at the top of your script/module)
This allows you to replace the new print function with your own:
The advantage is that this way your script will work just the same when you upgrade one day to Python 3.x.
Ps1: I did not try it out, but the print-as-function might just flush by default.
PS2: you might also be interested in my progressbar example.