我无法理解的 Python 打印行为 [英] Behavior of Python print which I am unable to understand

查看:40
本文介绍了我无法理解的 Python 打印行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码片段如下所示:

My code snippet look like this:

from time import sleep
for i in xrange(10):
    status = "hello%s" % str(i)
    status = status + chr(8)*(len(status)+1)
    sleep(1)
    print status

行为与

print status

print status,

现在,当我在 print status 之后使用逗号时,print 只输出到 stdout 一次.即在循环最后一次迭代之后,当我没有在 print status 之后放置那个逗号时,print 每次被调用时都会输出到 stdout(因为我期待它).

Now when i use a comma after print status then print outputs to stdout only once. i.e. after the loop iterates for the last time, where as when i don't put that comma after print status then print outputs to stdout each time it is called (as i expect it to).

我不明白下面发生了什么.谁能解释一下.谢谢:)

I dont understand what is happening underneath. Can anyone explain. thanks :)

推荐答案

控制台终端是行缓冲的,这意味着控制台缓冲区将在找到换行符 \n 时刷新,这解释了您看到的行为现在,因为当您执行 print status 时,print 将自动打印一个新行字符,该字符将在 print 后刷新控制台缓冲区,但是当您执行 print status, 时,打印将不添加新行,因此打印后不会刷新缓冲区.

The console terminal is line buffered which mean that the console buffer will be flushed when it will found a new line character \n , which explain the behavior that you see now, because when you do print status print will print automatically a new line character which will flush the console buffer after the print , but when you do print status, the print will not add the new line so the buffer will not be flushed after the print.

这是一篇关于缓冲的好文章,希望它能给你更多的见识:)

Here is a good article about buffering hope it can give you more insight :)

这篇关于我无法理解的 Python 打印行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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