在Python中键入效果

Par*_*jar 5 python sleep python-2.7

我想制作这样的程序,它从字符串中读取字符并在一段延迟后打印每个字符,所以它看起来像打字效果.

现在我的问题是睡眠功能不正常.长时间拖延后打印整句.

import sys
from time import sleep

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

我使用"sys.stdout.write"来删除字符之间的空格.

Reb*_*que 11

python 3中,您可以将调用替换sys.stdout为标准print调用:

for char in words:
    sleep(0.1)
    print(char, end='', flush=True)
Run Code Online (Sandbox Code Playgroud)


Jan*_*cak 5

你应该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()
Run Code Online (Sandbox Code Playgroud)

您的输出被缓冲的原因是需要执行系统调用以进行输出,系统调用既昂贵又耗时(因为上下文切换等).因此,用户空间库会尝试缓冲它,如果需要,您需要手动刷新它.

只是为了完整性...错误输出通常是非缓冲的(调试很困难).所以下面也会奏效.重要的是要意识到它被打印到错误输出.

import sys
from time import sleep

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