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

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

问题描述

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

对于某事:做点什么打印 '.',

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

解决方案

<块引用>

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

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

for _ in range(10):打印 '.',sys.stdout.flush()time.sleep(.2) # 或其他耗时的工作

或者对于 Python 3.x:

for _ in range(10):打印('.',结束='',冲洗=真)time.sleep(.2) # 或其他耗时的工作

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 '.',

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

Or for Python 3.x:

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

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

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