python`print`在循环中不起作用 [英] python `print` does not work in loop

查看:84
本文介绍了python`print`在循环中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将多个循环放在一起,并在最内部的循环中睡眠.例如:

I have multi loops in together and a sleep in the most inner loop. for example:

from time import sleep

for i in range(10):
    print i,
    for j in range(-5,5):
        if j > 0:
            print '.',
        else:
            print 'D',
        sleep(1)
    print ''

如果您运行该代码,您可能希望在 D 休眠 1 秒和另一个 D 并再次休眠后获得 i 值,直到到最后.

if you run the code, you may expected to get i value after it D sleep 1 second and another D and again sleep until to the end.

但结果不同,它等待 10 秒并打印 0 D D D D D D 的整行.... 并再次等待打印下一行.

but the result is difference, it waits 10 seconds and prints the whole line of 0 D D D D D D . . . . and waiting again to printing next line.

我发现打印末尾的逗号会导致此问题.我该如何解决?

I found the comma at the end of printing causes this problem. How can I solve it?

推荐答案

由于逗号的存在,输出缓冲到一个 \n.

Because of existence of comma, the output buffers until a \n.

您应该在每次打印后刷新 stdout 或使用 sys.stdout.write 并刷新缓冲区.

You should flush the stdout after every print or use sys.stdout.write and flush buffer.

定义您的打印方法:

import sys

def my_print(text):
    sys.stdout.write(str(text))
    sys.stdout.flush()

并在行尾打印 \n

这篇关于python`print`在循环中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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