为什么`print`内容不会立即显示在终端? [英] Why `print` content doesn't show immediately in terminal?

查看:113
本文介绍了为什么`print`内容不会立即显示在终端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于模拟的python脚本,运行 for 循环需要相当长的时间,并且每个循环需要不同的时间来运行,所以我打印一个在每个循环之后,作为监视它运行速度的方式以及在脚本运行时它通过 for 语句的程度。

I have a python script for simulation, it takes fairly long time to run through a for loop and each loop takes different time to run, so I print a . after each loop as a way to monitor how fast it runs and how far it went through the for statement as the script runs.

for something:
    do something
    print '.',

然而,当我在终端的iPython中运行脚本时,点不会逐个打印,而是一次打印所有这些当循环结束时,整个事情变得毫无意义。如何在运行时打印内联点?

However, as I run the script in iPython in terminal, the dots does not print one by one, instead it prints them all at once when the loop finishes, which made the whole thing pointless. How can I print the dots inline as it runs?

推荐答案



如何在运行时打印内联点?

How can I print the dots inline as it runs?


尝试刷新输出,如下所示:

Try flushing your output, like so:

for _ in range(10):
    print '.',
    sys.stdout.flush()
    time.sleep(.2)  # or other time-consuming work

这篇关于为什么`print`内容不会立即显示在终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆