Python中的打字效果 [英] Typing effect in Python

查看:85
本文介绍了Python中的打字效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样一个程序,它从字符串中读取字符并在一些延迟后打印每个字符,使其看起来像打字效果.

I want to make such program which reads characters from a string and prints each character after some delay so its look like typing effect.

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

Now my problem is sleep function is not working properly. It print whole sentence after long delay.

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"来删除字符之间的空格.

I use "sys.stdout.write" for removing whitespace between characters.

推荐答案

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

you should use sys.stdout.flush() after each iteration

问题是 stdout 是用换行符或手动用 sys.stdout.flush()

The problem is that stdout is flushed with the newline or manually with 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()

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

The reason why your output is buffered is that system call needs to be performed in order to do an output, system calls are expensive and time consuming (because of the context switch, etc). Therefore user space libraries try to buffer it and you need to flush it manually if needed.

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

Just for the sake of completeness ... Error output is usually non-buffered (it would be difficult for debugging). So following would also work. It is just important to realise that it is printed to the error output.

import sys
from time import sleep

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

这篇关于Python中的打字效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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