Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing effect in 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)

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

like image 897
Parth Gajjar Avatar asked Nov 30 '13 16:11

Parth Gajjar


1 Answers

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)
like image 54
Jan Vorcak Avatar answered Sep 28 '22 06:09

Jan Vorcak