Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command prompt can't write letter by letter? [duplicate]

import time
def textinput(txt,waittime=0.04):
    end = len(txt)
    letters = 0
    while end != letters:
        print(txt[letters], end = '')
        letters += 1
        time.sleep(waittime)
textinput('Hello there!')

This is basically my function for writing words letter by letter, it works flawlessly on IDLE when testing it, however, when I run it normally (and it opens up the command prompt), what I'm trying to write stays invisible, and then suddenly displays the words at once. Did I type something wrong, or is it command prompt's issue? I'm using windows 10.

like image 937
Pop Car Avatar asked Aug 26 '15 18:08

Pop Car


3 Answers

You don't need to use sys, you just need flush=True:

def textinput(txt,waittime=0.4):
    for letter in txt:
        print(letter, end = '',flush=True)
        time.sleep(waittime)

You can also simply iterate over the string itself.

like image 147
Padraic Cunningham Avatar answered Nov 02 '22 13:11

Padraic Cunningham


Output is probably buffered, trying flushing it by adding the following line after your print:

sys.stdout.flush()
like image 44
iobender Avatar answered Nov 02 '22 12:11

iobender


The issue most probably is the the standard output is not getting flushed automatically instead it is getting buffered, for your case to work, you should manually flush() stdout -

import time
import sys
def textinput(txt,waittime=0.04):
    end = len(txt)
    letters = 0
    while end != letters:
        print(txt[letters], end = '')
        sys.stdout.flush()
        letters += 1
        time.sleep(waittime)
textinput('Hello there!')
like image 2
Anand S Kumar Avatar answered Nov 02 '22 11:11

Anand S Kumar