Python中的打字效果


问题内容

我想做一个这样的程序,它从字符串中读取字符并在延迟一段时间后打印每个字符,因此它看起来像打字效果。

现在我的问题是睡眠功能无法正常工作。长时间延迟后打印整个句子。

import sys
from time import sleep

words = "This is just a test :P"
for char in words:
    sleep(0.5)
    sys.stdout.write(char)

我使用“ sys.stdout.write”删除字符之间的空格。


问题答案:

您应该sys.stdout.flush()在每次迭代后使用

问题是stdout用换行符刷新或用 sys.stdout.flush()

所以结果是

import sys
from time import sleep

words = "This is just a test :P"
for char in words:
    sleep(0.5)
    sys.stdout.write(char)
    sys.stdout.flush()

之所以要缓冲输出,是因为需要执行系统调用才能进行输出,系统调用既昂贵又耗时(由于上下文切换等)。因此,用户空间库尝试缓冲它,如果需要,您需要手动刷新它。

仅出于完整性考虑…错误输出通常是非缓冲的(调试起来很困难)。因此,下面的方法也可以。重要的是要意识到将其打印到错误输出。

import sys
from time import sleep

words = "This is just a test :P"
for char in words:
    sleep(0.5)
    sys.stderr.write(char)