Typing effect in Python

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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) 

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

回答1:

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

The problem is that stdout is flushed with the newline or manually with sys.stdout.flush()

So the result is

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) 


回答2:

You have to flush the stdout at each loop, to empty the buffer:

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

Without this, it just stored your string in the buffer and wait for an \n (or sufficient amount of characters to print), which come at the end of your loop....

More info :



回答3:

import sys from time import sleep  words = "Welcome to CB#SA.NET.CO" for char in words: sleep(0.1) sys.stdout.write(char) sys.stdout.flush() 


回答4:

In python 3, you can replace the calls to sys.stdout with standard print calls:

for char in words:     sleep(0.1)     print(char, end='', flush=True) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!