Python sleep() 禁止用逗号打印? [英] Python sleep() inhibit print with comma?

查看:31
本文介绍了Python sleep() 禁止用逗号打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想使用带有逗号 (2.6) 的打印,只要您不使用 time.sleep(),它就可以正常工作.

If I want to use the print with the comma (2.6), it works fine as long as you don't use time.sleep().

如果使用带有逗号的打印,然后调用睡眠;如果您处于循环中,该字符串将永远不会打印.

If you use the print with the comma, and then invoke sleep; the string will never print, if you are in a loop.

示例:

a=1
b=10
while a<b:
    print "yes",
    a=a+1

这行得通,你会看到在同一行上打印了 10 次 yes.但这行不通.

This works, you will see yes printed on the same line for 10 times. But this won't work.

a=1
b=10
while a<b:
    print "yes",
    time.sleep(1)
    a=a+1

期望是会打印yes;然后等待一秒钟,然后将打印下一个是.相反,您会看到 10 秒后打印出一串 10 yes.

The expectation is that there will be a yes printed; then there is a second of wait, and then the next yes will be printed. Instead, you will see a string of 10 yes printed after 10 seconds.

如果你使用 while 循环也是如此;只要循环正在运行,并且您有一个 sleep 语句,字符串就不会打印到最后.

Same goes if you use while loop; as long as the loop is running, and you have a sleep statement, the string won't print until the end.

要使其工作,请删除逗号.如果您想指定要在每个字符串之间等待多长时间,则无法在同一行上打印字符串.

To make it work, remove the comma. This makes impossible to print a string on the same line, if you want to specify how long you want to wait between each string.

这是打印功能的错误吗?

Is this a bug in the print function?

推荐答案

print 不会自动刷新您的输出.您需要手动执行此操作.这可以通过使用 sys 模块的 stdout.flush

print does not automatically flush your output. You need to manually do it. This can be done by using sys module's stdout.flush

import sys,time
a=1
b=10
while a<b:
    print "yes",
    sys.stdout.flush()
    time.sleep(1)
    a=a+1

这是防止 Python 使用缓冲 stdio 管道的另一种方法(感谢 巴内特)

Here is another way to prevent Python from using buffered stdio pipes (Thanks to abarnert)

使用 -u 选项执行你的程序

Execute your program by using the -u option as in

python -u filename.py

来自手册页.

-u
强制stdinstdoutstderr 完全无缓冲.

-u
Force stdin, stdout and stderr to be totally unbuffered.

Python3.3 的最后一种方法是使用 flush 参数到 打印函数

One final way from Python3.3 is to use the flush argument to the print function

输出是否缓冲通常由文件决定,但如果flush 关键字参数为真,流被强制刷新.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

在 3.3 版中更改:添加了 flush 关键字参数.

这篇关于Python sleep() 禁止用逗号打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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