为什么打印功能没有在正确的时间运行? [英] Why is the print function not running at the right time?

查看:43
本文介绍了为什么打印功能没有在正确的时间运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

import time as t

print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)

我的问题是所有打印命令都在 sleep 命令之后执行,这不是我想要的输出.

My problem is that all the print commands are executed after the sleep commands, and that's not my intended output.

推荐答案

这是因为输出缓冲.在打印换行符之前不会刷新缓冲区.由于您使用了 end=' ',因此每个单词后没有换行符,因此在脚本结束之前不会刷新缓冲区.

It's because of output buffering. The buffer isn't flushed until a newline is printed. Since you used end=' ', there's no newline after each word, so the buffer isn't flushed until the script ends.

您可以使用 flush=True 选项强制它立即刷新.

You can use the flush=True option to force it to flush immediately.

import time as t
import sys

print('hello', end=' ', flush=True)
t.sleep(1)
print('hello', end=' ', flush=True)
t.sleep(1)
print('hello', end=' ', flush=True)
t.sleep(1)

这篇关于为什么打印功能没有在正确的时间运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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