使用使用“ end”属性的打印功能,“ time.sleep()”是否不能在for循环内使用?

时间:2019-07-05 04:49:37

标签: python-3.x delay

所以,我最近才在学习python,并且正在玩一些代码。我想在循环中以一定的延迟打印一些没有换行符的字符。我在for循环中使用了time.sleep()函数。但是,它所做的只是一次将输出延迟到循环中所需的全部时间,然后立即打印出字符。

我确实尝试了不带“ end”属性的情况,并且效果很好。但是,我不想换行。

from time import sleep
print("starting the progress bar")


for i in range(50):
    sleep(0.1)
    print("#", end = '')

我希望输出打印一个字符,并延迟打印另一个字符。但是,脚本会延迟50秒0.1秒,然后立即打印出所有字符

5 个答案:

答案 0 :(得分:1)

由于python被行缓冲,它将在打印标准输出之前等待换行。

解决方案1:

将PYTHONUNBUFFERED = 1添加到您的env.var:

export PYTHONUNBUFFERED=1

这将使输出立即转储

解决方案2:

使用python 3时,可以使用flush = True

for i in range(50):
    sleep(0.1)
    print("#", end = '', flush=True)

答案 1 :(得分:0)

默认情况下,Python是行缓冲的。只要您print没有换行符,就会收集输出但不会显示。您必须强制flush输出。

from time import sleep
print("starting the progress bar")


for i in range(50):
    sleep(0.1)
    print("#", end = '', flush=True)

请注意,无论您用于查看 还是什么,输出都可能是行缓冲的。不能从您的脚本中更改。

答案 2 :(得分:0)

我刚刚在reddit上找到了解决方案。

reddit comment on why it doesn't work and how beginners fall into the same pitfall

因此,它与缓冲有关。

这是可行的代码;

from time import sleep
print("starting the progress bar")


for i in range(50):
    sleep(0.1)
    print("#", end = '', flush = True)

答案 3 :(得分:0)

运行程序时可以使用-u选项。

$ man python3


PYTHON(1)                                                            PYTHON(1)

...

       -u     Force  the  stdout  and  stderr  streams to be unbuffered.  This
              option has no effect on the stdin stream.

像这样运行:python3 -u file.py


或者,您可以在shell中设置PYTHONUNBUFFERED环境变量

       PYTHONUNBUFFERED
              If this is set to a non-empty string it is equivalent to  speci-
              fying the -u option.

就像这样:PYTHONUNBUFFERED="yes" python3 file.py


最后,您可以使用flush=True作为其他答案。

答案 4 :(得分:-1)

您使用了end in print,因此您可以正常工作,但是由于结束,整个输出将在range(50)和sleep(0.1)之后显示

    from time import sleep
    import sys
    print("starting the progress bar")

    for x in range(50):
        print("#", end = '')
        sleep(0.1)
        sys.stdout.flush()

使用此